在 C++ 程序中交叉引用包含的头文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1429336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross referencing included headers in c++ program
提问by banDedo
I am curious about a scenario set up like the following example:
我对设置如下示例的场景很好奇:
Here is code that would be placed in a file called Header1.h:
以下代码将放置在名为 Header1.h 的文件中:
#ifndef HEADER1_H
#define HEADER1_H
#include "Header2.h"
class Class1
{
Class2 class2Instance;
};
#endif
Here is code that would be placed in a file called Header2.h:
以下代码将放置在名为 Header2.h 的文件中:
#ifndef HEADER2_H
#define HEADER2_H
#include "Header1.h"
class Class2
{
Class1 class1Instance;
};
#endif
I get error messages when I do this (because of the includes I assume), but it feels like I would need to do this in order to include each of the objects in the separate classes. Can anyone help me accomplish this, what am I doing wrong?
执行此操作时我收到错误消息(因为我假设了包含),但感觉我需要这样做才能将每个对象包含在单独的类中。谁能帮我完成这个,我做错了什么?
回答by John Millikin
The problem is that the size of Class1 depends on Class2, and vice-versa. Therefore, there's no way to calculate the size for either one. Forward-declare one of the classes, and change one of the attributes to be a pointer or reference:
问题是 Class1 的大小取决于 Class2,反之亦然。因此,无法计算任何一个的大小。向前声明其中一个类,并将其中一个属性更改为指针或引用:
#ifndef HEADER2_H
#define HEADER2_H
class Class1;
class Class2
{
Class1 *class1Instance;
// or
Class1 &class1Instance;
};
#endif
回答by sadhen
回答by fbrereto
The two structures infinitely recurse on one another -- to know Class1
's size you need to know the size of Class2
which requires the size of Class1
, etc. The workaround for this is to use a pointer in at least one of the cases:
这两个结构相互无限递归——要知道Class1
的大小,您需要知道其大小Class2
需要 的大小Class1
等。解决方法是在至少一种情况下使用指针:
#ifndef HEADER1_H
#define HEADER1_H
class Class2; // no need to include Header2
class Class1
{
Class2* class2Instance;
}
#endif
回答by Ferruccio
You can't have Class2 contain an instance of Class1 AND have Class1 contain an instance of Class2. What you can do is have each class contain a reference or pointer to and instance of the other class type (with appropriate forward references). i.e.
您不能让 Class2 包含 Class1 的实例并且让 Class1 包含 Class2 的实例。您可以做的是让每个类都包含一个引用或指向另一个类类型的实例的指针(具有适当的前向引用)。IE
class Class2;
class Class1
{
Class2& class2Instance;
};
class Class1;
class Class2
{
Class1& class1Instance;
};
回答by Randolpho
What you have is a classic circular reference. It's already been discussedhere on Stack Overflow. Just apply the accepted answer on that thread, while substituting "struct" for "class", and you're golden.
你所拥有的是一个经典的循环引用。它已经讨论过了这里堆栈溢出。只需在该线程上应用已接受的答案,同时将“结构”替换为“类”,您就是金子。
Edited for clarity
为清晰起见进行了编辑