两个类可以使用 C++ 互相查看吗?
所以我有一个 A 类,我想在其中调用一些 B 类函数。所以我包括“bh”。但是,在 B 类中,我想调用 A 类函数。如果我包含“啊”,它最终会陷入无限循环,对吗?我能做什么呢?
So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
仅将成员函数声明放在头文件 (.h) 中,并将成员函数定义放在实现文件 (.cpp) 中。那么您的头文件不需要相互包含,并且您可以在任一实现文件中包含这两个头文件。
如果您还需要在成员签名中引用其他类,则可以使用前向声明:
这使您可以使用指针和引用类型(
A*
和A&
>),尽管不是A
本身。它也不让你打电话给会员。例子:
Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.
For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:
This lets you use pointer and reference types (
A*
andA&
), though notA
itself. It also doesn't let you call members.Example:
每个类(A 和 B)应该有一个头文件和一个实现文件。
每个头文件(例如
Ah
)不应包含其他头文件(例如Bh
),但可以包含对其他类的前向引用(例如类似的语句) class B;
),然后可以在其声明中使用对另一个类的指针和/或引用(例如,class A
可以包含B*
作为数据成员和/或作为方法参数)。每个CPP 文件(例如
A.cpp
)可以包含多个头文件(例如Ah
和Bh
)。建议每个 CPP 文件首先包含自己的头文件(例如A.cpp
应包含Ah
,然后包含Bh
,而B.cpp
应包含Bh
,然后包含Ah
)。每个头文件应该只包含声明,而不是类的定义:例如,它将列出类方法的签名,但不列出方法体/实现(方法体/实现将位于
.cpp
文件,不在头文件中)。由于头文件不包含实现细节,因此它们不依赖(不需要查看)其他类的细节;他们最多需要知道,例如,B
是一个类的名称:它可以从前向声明中获得,而不是通过在另一个头文件中包含一个头文件。Each class (A and B) should have a header file and an implementation file.
Each header file (e.g.
A.h
) should not include the other header file (e.g.B.h
) but may include a forward reference to the other class (e.g. a statement likeclass B;
), and may then use pointers and/or references to the other class in its declaration (e.g.class A
may contain aB*
as a data member and/or as a method parameter).Each CPP file (e.g.
A.cpp
) may include more than one header file (e.g.A.h
andB.h
). It's recommended that each CPP file should include its own header file first (e.g.A.cpp
should includeA.h
and thenB.h
, whereasB.cpp
should includeB.h
and thenA.h
).Each header file should contain only the declaration, and not the definition of the class: for example it will list the signatures of the class' methods, but not the method bodies/implementations (the method bodies/implementations will be in the
.cpp
file, not in the header file). Because the header files don't contain implemention details, they therefore don't depend on (don't need to see) details of other classes; at most they need to know that, for example,B
is the name of a class: which it can get from a forward declaratin, instead of by including a header file in another header file.您还可以使用前向声明来解决该问题。
You can also use forward declarations to get around the issue.
尝试将
#ifndef
、#define
和#endif
放在 .h 文件周围。Try putting
#ifndef
,#define
and#endif
around your .h files.