以下代码使用VC++6编译。我不明白为什么我会收到以下代码的编译错误 C2079: 'b' uses undefined class 'B'
。
B 类来源
#include "B.h"
void B::SomeFunction()
{
}
B 类 header
#include "A.h"
struct A;
class B
{
public:
A a;
void SomeFunction();
};
构造一个 header
#include "B.h"
class B;
struct A
{
B b;
};
如果我将 B 类 header 更改为以下内容,则不会出现错误。但是 header 声明不会在顶部!
带有奇怪 header 声明的 B 类 header
struct A;
class B
{
public:
A a;
void SomeFunction();
};
#include "A.h"
最佳答案
为了定义一个类或结构,编译器必须知道类的每个成员变量有多大。前向声明不会这样做。我只见过它用于指针和(较少)引用。
除此之外,您在这里尝试做的事情无法完成。您不能有一个类 A 包含另一个类 B 的对象,而另一个类 B 包含类 A 的对象。但是,您可以有类A 包含指向类 B 的指针,类 B 包含类 A 的对象。
B.cpp
#include "B.h"
void B::SomeFunction()
{
}
B.h
#ifndef __B_h__ // idempotence - keep header from being included multiple times
#define __B_h__
#include "A.h"
class B
{
public:
A a;
void SomeFunction();
};
#endif // __B_h__
啊啊
#ifndef __A_h__ // idempotence - keep header from being included multiple times
#define __A_h__
#include "B.h"
class B; // forward declaration
struct A
{
B *b; // use a pointer here, not an object
};
#endif // __A_h__
两点。首先,一定要使用某种形式的幂等性来防止每个编译单元多次包含 header 。其次,了解在 C++ 中,类和结构之间的唯一区别是默认可见性级别——类默认使用私有(private)可见性,而结构默认使用公共(public)可见性。以下定义在 C++ 中在功能上是等效的。
class MyClass
{
public: // classes use private visibility by default
int i;
MyClass() : i(13) { }
};
struct MyStruct
{
int i;
MyStruct() : i(13) { }
};
关于c++ - 类的前向声明在 C++ 中似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1885471/