c++ - 关于头文件C++中的类声明

标签 c++

问题来了。我需要编写包含两个类的头文件,比如 A 类和 B 类。

在 A 类中,我有使用 B 类对象的函数,反之亦然,即在 B 类中,我有使用 A 类对象的函数。

如果 A 先声明,那么会出现类 B 尚未声明的错误。 如何处理?我尝试在声明 B 类之后声明 A 类的函数:

void classA::myfunc (classB *b);

但是我得到了一个错误,没有声明函数 myfunc。 有C++经验的人,怎么办?

添加: 这是一个很好的链接 about header

最佳答案

如果您需要一个指向 header 上的类的指针,而不是完整的对象,只需添加前向声明,不要包含指针类的 header 。

我确定您只是使用指针来访问那些引用了另一个类的类,不是吗?你知道,因为如果你使用实例,你就会得到一个实例循环。使用前向声明。

这是一个如何使用前向声明的示例:

啊啊

class B;
class C;
class D;
class E;

class A {
    B* pointer; //To just have a pointer to another object.
    void doThings(C* object); //if you just want to tell that a pointer of a object is a param
    D* getThings(); //if you wanna tell that a pointer of such class is a return.
    E invalid(); //This will cause an error, because you cant use forward declarations for full objects, only pointers. For this, you have to use #include "E.h".
};

为了说明如何让一个类提到一个指向其类型的类:

B.h

class A;
class B {
    A* pointer; //That can be done! But if you use a includes instead of the forward declarations, you'll have a include looping, since A includes B, and B includes A.
}

正如 Tony Delroy 所提到的(非常感谢他)你不应该总是使用这种设计。它由 C++ 编译器提供,但这不是一个好的做法。最好是提供引用 header ,这样您的代码将如下所示:

啊啊

#include "B.fwd.h"
#include "C.fwd.h"
#include "D.fwd.h"
#include "E.fwd.h"

class A {
    B* pointer; //To just have a pointer to another object.
    void doThings(C* object); //if you just want to tell that a pointer of a object is a param
    D* getThings(); //if you wanna tell that a pointer of such class is a return.
    E invalid(); //This will cause an error, because you cant use forward declarations for full objects, only pointers. For this, you have to use #include "E.h".
};

你的转发标题是这样的:

B.fwd.h:

class B;

在你的 fwds 中,你应该有你的类前向声明​​,以及它附带的任何类型定义。

我没有提到 #pragma once ,或 #ifndef B.H...你知道他们会在那里 :D

您的代码将遵循 <iosfwd> 定义的标准并且更好地维护,特别是如果它们是模板。

关于c++ - 关于头文件C++中的类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632430/

相关文章:

c++ - 编译器如何处理 const 函数?

c++ - 访问构建 boost::thread 的可调用对象

c++ - 只需添加一些文档即可触发重新编译 : Is there a solution?

c++ - std::streams 已经可以移动了吗?

python - 一起调试boost暴露的Python和C++

c++ - 如何使用 QT 在 Windows 中启动进程?

c++ - 按键时发送输出

c++ - 对静态成员的 const 引用

c++ - 什么是用于序号排序的 QT 或开源 C++ 模板

c++ - 最大出现次数