每当类声明仅使用另一个类作为指针时,使用类前向声明而不是包含头文件是否有意义,以便先发制人地避免循环依赖的问题?所以,而不是:
//file C.h
#include "A.h"
#include "B.h"
class C{
A* a;
B b;
...
};
Run Code Online (Sandbox Code Playgroud)
改为:
//file C.h
#include "B.h"
class A;
class C{
A* a;
B b;
...
};
//file C.cpp
#include "C.h"
#include "A.h"
...
Run Code Online (Sandbox Code Playgroud)
有什么理由不尽可能不这样做吗?
考虑以下两种情况(编辑只是为了完成整个问题并使其更清晰)
案例1 :(如下面正确提到的那样编译)
//B.h
#ifndef B_H
#define B_H
#include "B.h"
class A;
class B {
A obj;
public:
void printA_thruB();
};
#endif
//B.cpp
#include "B.h"
#include <iostream>
void B::printA_thruB(){
obj.printA();
}
//A.h;
#ifndef A_H
#define A_H
#include "A.h"
class A {
int a;
public:
A();
void printA();
};
#endif
//A.cpp
#include "A.h"
#include <iostream>
A::A(){
a=10;
}
void A::printA()
{
std::cout<<"A:"<<a<<std::endl;
}
//main.cpp
#include "B.h"
#include<iostream>
using namespace std;
int main()
{
B obj;
obj.printA_thruB();
}
Run Code Online (Sandbox Code Playgroud)
案例2 :(唯一的修改......没有编译错误)
//B.h
#include …Run Code Online (Sandbox Code Playgroud) 我很清楚何时能够/不能使用前瞻性声明,但我仍然不确定一件事.
假设我知道我迟早要包括一个标题来取消引用A类的对象.我不清楚是否更有效地做类似的事情.
class A;
class B
{
A* a;
void DoSomethingWithA();
};
Run Code Online (Sandbox Code Playgroud)
然后在cpp有类似的东西..
#include "A.hpp"
void B::DoSomethingWithA()
{
a->FunctionOfA();
}
Run Code Online (Sandbox Code Playgroud)
或者我也可以首先在B的头文件中包含A的标题?如果前者效率更高,那么如果有人清楚地解释了为什么我怀疑它与编译过程有关,我可以随时了解更多信息,我会很感激.