背景
在学习c++设计模式的Pimpl时,一共编写了三个文件:try.h、try.cpp和test.cpp,其中主函数包含在test.cpp中,并在该文件中调用try.h头文件中自定义的类;try.h中的具体实现细节被封装在try.cpp中。
//try.h
class Line
{
public:
Line(int x1, int y1, int x2, int y2);
~Line();
void printLine() const;
private:
class LineImpl;
LineImpl *_pimpl;
};
//try.cpp
#include<iostream>
#include"try.h"
using namespace std;
class Line::LineImpl
{
public:
LineImpl(int x1, int y1, int x2, int y2);
void printLineImpl() const;
private:
class Point
{
public:
Point(int x=-1, int y=2)
:_x(x)
,_y(y)
{
cout << "Point()" << endl;
}
void printPoint() const;
private:
int _x;
int _y;
};
Point _pt1;
Point _pt2;
};
void Line::LineImpl::Point::printPoint() const
{
cout << "x=" << _x << ",y=" << _y << endl;
}
Line::LineImpl::LineImpl(int x1, int y1, int x2, int y2)
:_pt1(x1, y1)
,_pt2(x2, y2)
{
cout << "LineImpl()" << endl;
}
void Line::LineImpl::printLineImpl() const
{
_pt1.printPoint();
_pt2.printPoint();
}
Line::Line(int x1, int y1, int x2, int y2)
:_pimpl(new LineImpl(x1, y1, x2, y2))
{
cout << "Line()" << endl;
}
Line::~Line()
{
delete _pimpl;
cout << "~Line()" << endl;
}
void Line::printLine() const
{
_pimpl->printLineImpl();
}
//test.cpp
#include"try.h"
int main()
{
Line ln(-1,-2,-3,-4);
ln.printLine();
}
此时直接使用vscode的编译运行按钮,会产生以下报错信息:
原因分析
可以看到,由vscode自动产生的编译指令中,只对test.cpp进行了编译,忽略了try.cpp,导致头文件中自定义类的具体实现细节没有被链接到test.cpp中,因此报错显示没有找到这些类的具体定义。
解决方法
为简单起见,我们直接使用g++编译命令对上述两个.cpp源文件进行手动编译,输入如下命令:
g++ .\test.cpp .\try.cpp -o .\test
./test.exe
此时便能得到正确答案: