循环 C++ 头文件包括 [英] Circular C++ Header Includes

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

问题描述

在一个项目中,我有 2 个类:

In a project I have 2 classes:

//mainw.h

#include "IFr.h"
...
class mainw
{
public:
static IFr ifr;
static CSize=100;
...
};

//IFr.h

#include "mainw.h"
...
class IFr
{
public float[mainw::CSize];
};

但我无法编译此代码,在 static IFr ifr; 行出现错误.这种交叉包含是否被禁止?

But I cannot compile this code, getting an error at the static IFr ifr; line. Is this kind of cross-inclusion prohibited?

推荐答案

这种交叉包含是否被禁止?

Is this kind of cross-inclusions are prohibited?

是的.

一种变通方法是说 mainw 的 ifr 成员是一个引用或一个指针,这样前向声明就可以了,而不是包含完整的声明,例如:

A work-around would be to say that the ifr member of mainw is a reference or a pointer, so that a forward-declaration will do instead of including the full declaration, like:

//#include "IFr.h" //not this
class IFr; //this instead
...
class mainw
{
public:
static IFr* ifr; //pointer; don't forget to initialize this in mainw.cpp!
static CSize=100;
...
}

或者,在单独的头文件中定义 CSize 值(以便 Ifr.h 可以包含这个其他头文件,而不是包含 mainw.h).

Alternatively, define the CSize value in a separate header file (so that Ifr.h can include this other header file instead of including mainw.h).

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

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