c ++头文件相互包含 [英] c++ header files including each other mutually

查看:133
本文介绍了c ++头文件相互包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类都定义在单独的头文件中。每个文件都有一个类型为其他类的字段。现在我包括在每个文件的标题其他文件的标题,但编译器生成错误。

I have two classes both defined in separate header files. Each file has a field that is type of other class. Now I included in header of each file the header of other file, but compiler is generating errors. What am i missing?

推荐答案

你不能让每个类都有一个字段是其他类的类型。这将是一个递归定义,并且编译器将无法对其进行任何意义,即使您通过在同一头文件中声明两个类来绕过头文件包含问题。

You cannot have each class have "a field that is type of other class"; that would be a recursive definition and the compiler would not be able to make any sense out of it, even if you bypassed the header file inclusion problem by declaring both classes within the same header file.

所以,两个字段之一必须是一个指针到另一个类的实例,并且该类必须在类的头文件中使用forward声明包含指针。

So, one of the two fields must be a pointer to an instance of the other class, and that class will have to be declared with a forward declaration within the header file of the class containing the pointer.

修正

抱歉,答案是不完整的没有例子,所以,这里是:

Apologies, it occurred to me that my answer was incomplete without an example, so, here it is:

文件Ah:

/* This is called a "forward declaration".  We use it to tell the compiler that the 
   identifier "B" will from now on stand for a class, and this class will be defined 
   later.  We will not be able to make any use of "B" before it has been defined, but 
   we will at least be able to declare pointers to it. */
class B;

class A
{
    /* We cannot have a field of type "B" here, because it has not been defined yet. 
       However, with the forward declaration we have told the compiler that "B" is a 
       class, so we can at least have a field which is a pointer to "B". */
    B* pb; 
}

文件Bh:

#include "A.h"

class B
{
   /* the compiler now knows the size of "A", so we can have a field of type "A". */
   A a;
}

这篇关于c ++头文件相互包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆