假如我们有两个类t1和t2,我们要在t1的show方法中调用t2的show方法,在t2的show方法中调用t1的show方法,那么我们必然要在两个类的成员变量中加入对应类的实体对象。(我知道这是个死循环啦,不要在意这些细节啦,你主要看我怎么解决这个问题的)
.h文件如下
#pragma once
#include"t2.h"
class t1
{
public:
void show();
private:
t2 T2;
};
#pragma once
#include"t1.h"
class t2
{
public:
void show();
private:
t1 T1;
};
.cpp文件如下
#include"../include/t1.h"
void t1::show()
{
T2.show();
}
#include"../include/t2.h"
void t2::show()
{
T1.show();
}
这时进行编译就会报错
t2.h(8,5): error C3646: “T1”: 未知重写说明符
t1.h(8,5): error C3646: “T2”: 未知重写说明符
为了解决这个问题,可以使用前向声明来代替头文件的包含。
首先将t1.h和t2.h中,对应包含的头文件去掉,并在t1中声明t2,在t2中声明t1,并将实体对象改为对应的实体指针。
t1.h
#pragma once
class t2;
class t1
{
public:
void show();
private:
t2* T2;
};
t2.h
#pragma once
class t1;
class t2
{
public:
void show();
private:
t1* T1;
};
然后在t1.cpp和t2.cpp中包含对应的头文件即可。
t1.cpp
#include"../include/t1.h"
#include"../include/t2.h"
void t1::show()
{
T2->show();
}
t2.cpp
#include"../include/t2.h"
#include"../include/t1.h"
void t2::show()
{
T1->show();
}
成功运行