前置声明与C++头文件互相包含导致的error: ‘xxx‘ does not name a type问题

在一个源文件中,要声明或定义一个类的指针时,必须在使用前声明或定义该类,因此下面的代码会报错:

class A
{
public:
    B *b;
};

class B
{
public:
    A *a;
};

int main()
{
    return 0;
}


报错为“error: ‘B’ does not name a type”,就是因为在A类中使用B *b之前没有声明或定义B类,如果在第一行加上一句前置声明(forward declaration)“class B;”,就不会有这样的问题了。
而在头文件互相包含时,也会引发“error: ‘xxx’ does not name a type”,其报错原因和上面的代码是相同的,请看下面的代码:
a.h:

#ifndef A_H_INCLUDED
#define A_H_INCLUDED

#include "b.h"

class A
{
public:
    B *b;
};

#endif // A_H_INCLUDED


b.h:

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

#include "a.h"

class B
{
public:
    A *a;
};

#endif // B_H_INCLUDED


main.cpp:

#include "a.h"
#include "b.h"

int main()
{
    return 0;
}


编译就会报错:“error: ‘A’ does not name a type”,为什么会这样呢?我们看看a.h经过预处理会展开成什么样子呢,预处理命令为“gcc -E -o a.i a.h”:

# 1 "a.h"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.h"

# 1 "b.h" 1

# 1 "a.h" 1
# 5 "b.h" 2

class B
{
public:
    A *a;
};
# 5 "a.h" 2

class A
{
public:
    B *b;
};


忽略以“#”开头的行,我们发现它现在和开头的那个源文件几乎是一样的,只是类的顺序交换了,因此出错原因和开头的那个源文件是一样的。
解决方法也很简单,把a.h的“#include “b.h””替换为B类的前置声明“class B;”,在b.h中也进行类似的修改。这样的话,就不会导致问题了。当然,这么做是有前提的:在A类中的成员只有B类的指针,而不能有B类的变量;同时不能在A类头文件中访问B类的成员或成员函数。无论哪种情况A类都需要知道B类的大小或其他细节,前置声明无法提供这些细节,又会出现类似“error: field ‘b’ has incomplete type ‘B’”这样的问题。
 

猜你喜欢

转载自blog.csdn.net/weixin_58045467/article/details/130722016
今日推荐