c++ - 类的前向声明在 C++ 中似乎不起作用

标签 c++ header compilation declaration forward-declaration

以下代码使用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/

相关文章:

c++ - 从 R 覆盖 C++ 编译标志的系统默认值

xcode - 在 cocoapods podspec 文件中定义 header 搜索路径

c++ - C Header 定义顺序/位置

C++ 不能使用另一个文件中的类

c - 我应该自己优化我的代码还是让编译器/gcc 来做

Windows 访问冲突的 C++ 调用堆栈

c++ - 在循环期间收到 "Exception Thrown"

java - 在内部编译类时类路径不起作用?

c - 在C文件中包含源文件

c++ - 好友定义不适用于 gcc4.9