How can I declare classes that refer to each other?(如何声明相互引用的类?)
问题描述
自从我使用 C++ 已经很长时间了,我在类相互引用时遇到了一些麻烦.
It's been a long time since I've done C++ and I'm running into some trouble with classes referencing each other.
现在我有类似的东西:
a.h
class a
{
public:
a();
bool skeletonfunc(b temp);
};
b.h
class b
{
public:
b();
bool skeletonfunc(a temp);
};
由于每个人都需要对另一个人的引用,我发现我不能在顶部执行彼此的#include,否则我最终会陷入各种奇怪的循环.
Since each one needs a reference to the other, I've found I can't do a #include of each other at the top or I end up in a weird loop of sorts with the includes.
那么我怎样才能让 a
可以使用 b
反之亦然,而不会造成循环 #include 问题?
So how can I make it so that a
can use b
and vice versa without making a cyclical #include problem?
谢谢!
推荐答案
你必须使用前向声明:
a.h
class b;
class a
{
public:
a();
bool skeletonfunc(b temp);
}
然而,在许多情况下,这会迫使您在方法调用或成员变量中使用引用或指针,因为您不能在两个类头中都拥有完整的类型.如果必须知道类型的大小,则需要使用引用或指针.但是,如果只需要方法声明,则可以使用该类型.
However, in many situations, this can force you to work with references or pointers in your method calls or member variables, since you can't have the full types in both class headers. If the size of the type must be known, you need to use a reference or pointer. You can, however, use the type if only a method declaration is required.
这篇关于如何声明相互引用的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何声明相互引用的类?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01