交叉引用 C++ 程序中包含的标头

Cross referencing included headers in c++ program(交叉引用 C++ 程序中包含的标头)
本文介绍了交叉引用 C++ 程序中包含的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

#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:

#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?

解决方案

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++ 程序中包含的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Clang Tool (libtooling): set header search path to standard libs headers. Foundation framework(Clang 工具 (libtooling):将标头搜索路径设置为标准库标头.基础框架)
C++ Library Include(C++ 库包含)
How can I get the contents of a file at build time into my C++ string?(如何在构建时将文件的内容获取到我的 C++ 字符串中?)
C++ previous definition error(C++以前的定义错误)
Writing or Copying Visual C++ console output to text file(将 Visual C++ 控制台输出写入或复制到文本文件)
C++ class, its base class and circular include includes(C++ 类,它的基类和循环包含包括)