为什么声明您作为头文件包含的类?
#include "TreeCallObj.h"
#include "TreeDevObj.h"
#include "TreeDevCallObj.h"
class TreeCallObj; //what is the purpose of this line ?
class TreeDevObj; //what is the purpose of this line ?
class TreeDevCallObj; //what is the purpose of this line ?
class Apple
{
public:
...
private:
...
}
Run Code Online (Sandbox Code Playgroud)
考虑一下:
//a.h
#ifndef A_H
#define A_H
#include "b.h"
class A
{
B* b;
};
#endif
//b.h
#ifndef B_H
#define B_H
#include "a.h"
class B
{
A* a;
};
#endif
Run Code Online (Sandbox Code Playgroud)
现在你尝试将其中一个文件包含在另一个文件中,比如说#include "a.h".
编译器将其解析为:
#ifndef A_H
#define A_H
Run Code Online (Sandbox Code Playgroud)
很好 - A_H没有定义
#include "b.h"
Run Code Online (Sandbox Code Playgroud)
尝试粘贴内容:
#ifndef B_H
#define B_H
Run Code Online (Sandbox Code Playgroud)
好的,因为B_H没有定义
#include "a.h"
Run Code Online (Sandbox Code Playgroud)
这不会定义A,因为A_H是定义的.接下来,我们有
class B
{
A* a;
};
Run Code Online (Sandbox Code Playgroud)
这将导致错误,因为A在使用之前未定义或声明.
前方声明解决了这个问题.
当然,对此最好的解决方案是根本不包括(除非你绝对必须).
小智 5
这条线的目的是什么?
理想情况下没有.这是多余的.
然而,正如@Luchian Grigore指出的那样,可能存在如此设计糟糕的代码,由于包含警卫和交叉包含的使用不正确,可能需要进行前瞻性声明.