我有三个类,A,B和C.C类包括A和B类型的对象。在C的.cpp文件中,当我尝试使用A或B方法时(在这种情况下,'print'方法我写过)在A和B类型的对象上,我得到“方法'printA'未解析”。我在C.cpp中包含了A.h,B.h,A.cpp和B.cpp,并在C.h.中编写了“A类”和“B类”。如何让我的C.cpp文件访问A和B的方法?
以下是我目前为C.cpp文件所做的事情:
#include "C.h"
#include "A.h"
#include "A.cpp"
#include "B.h"
#include "B.cpp"
using namespace std;
void C::printC(){
a.printA();
b.printB();
}
其中'a'和'b'被定义为C.h文件中A和B类型的对象。
答案 0 :(得分:2)
在.h
文件中,您包含类的声明,而.cpp
文件应包含定义。
您需要直接或通过间接包含所有使用的声明,但不包括定义(如果不是内联或模板)。
#ifndef X_HEADER
#define X_HEADER
struct X
{
void printX();
};
#endif
#ifndef Y_HEADER
#define Y_HEADER
struct Y
{
void printY();
};
#endif
#ifndef Z_HEADER
#define Z_HEADER
#include "X.h"
#include "Y.h"
struct Z
{
X x;
Y y;
void printZ();
};
#endif
#include <iostream>
#include "X.h" // *
void X::printX () { std::cout << "X"; }
#include <iostream>
#include "Y.h" // **
void Y::printY() { std::cout << "Y"; }
#include "Z.h" // also includes X.h and Y.h due to * and **
// no need to include X.h and Y.h seperately here
// also no need to include any cpp file
void Z::printZ()
{
x.printX();
y.printY();
}
然后,您需要单独编译X.cpp
,Y.cpp
和Z.cpp
,并将其与包含int main(/**/)
函数的编译单元一起链接到可执行文件中。