交叉引用在c ++程序中包含头文件 [英] Cross referencing included headers in c++ program
问题描述
我对以下示例设置的方案感到好奇:
I am curious about a scenario set up like the following example:
这里是放置在名为Header1.h的文件中的代码:
Here is code that would be placed in a file called Header1.h:
#ifndef HEADER1_H
#define HEADER1_H
#include "Header2.h"
class Class1
{
Class2 class2Instance;
};
#endif
这里是放在一个文件Header2.h:
Here is code that would be placed in a file called 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?
推荐答案
问题是Class1的大小取决于Class2,反之亦然。因此,没有办法计算任一个的大小。向前声明一个类,并将其中一个属性更改为指针或引用:
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:
#ifndef HEADER2_H
#define HEADER2_H
class Class1;
class Class2
{
Class1 *class1Instance;
// or
Class1 &class1Instance;
};
#endif
这篇关于交叉引用在c ++程序中包含头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!