问题的提出:
首先,要分别在两个文件中实现以下两个类
class Object
{
public:
NewType ToType();
};
class NewType : public Object
{
}
-------------------------------------------------------------------------------- 做法1 ---------------------------------------------------------
//在文件Object.h 中定义
#include "NewType.h"
class Object
{
public:
NewType ToType();
};
//在文件NewType.h 中定义
#include "Object.h"
class NewType : public Object
{
}
将产生错误:
"warning C4182: #include nesting level is 363 deep; possible infinite recursion"
"fatal error C1076: compiler limit : internal heap limit reached; use /Zm to specify a higher limit"
原因是两个文件互相包含,导致包含的层次太深
-------------------------------------------------------------------------------- 做法2 ---------------------------------------------------------
//在文件Object.h 中定义
#include "NewType.h"
#ifndef _OBJECT_H
#define _OBJECT_H
class Object
{
public:
NewType ToType();
};
#endif
//在文件NewType.h 中定义
#include "Object.h"
#ifndef _NEWTYPE_H
#define _NEWTYPE_H
class NewType : public Object
{
}
#endif
错误依旧
-------------------------------------------------------------------------------- 做法3 ---------------------------------------------------------
//在文件Object.h 中定义
#ifndef _OBJECT_H
#define _OBJECT_H
#include "NewType.h"
class Object
{
public:
NewType ToType();
};
#endif
//在文件NewType.h 中定义
#include "Object.h"
#ifndef _NEWTYPE_H
#define _NEWTYPE_H
class NewType : public Object
{
}
#endif
产生错误:
"error C2504: 'Object' : base class undefined"
-------------------------------------------------------------------------------- 做法4 ---------------------------------------------------------
//在文件Object.h 中定义
#include "NewType.h"
#ifndef _OBJECT_H
#define _OBJECT_H
//位置
class Object
{
public:
NewType ToType();
};
#endif
//在文件NewType.h 中定义
#ifndef _NEWTYPE_H
#define _NEWTYPE_H
#include "Object.h"
class NewType : public Object
{
}
#endif
产生错误:
"error C2146: syntax error : missing ';' before identifier 'ToType'"
"error C2501: 'NewType' : missing storage-class or type specifiers"
原因是不能识别NewType类
解决方案:
于是在"位置"加上前向引用声明
class NewType;
编译通过
但采用此种做法,类的定义和实现部分不能为内联函数,或者报错
"error C2027: use of undefined type 'NewType'"
在VC++编程中,当两个文件互相包含类定义时,会导致编译错误。例如,`Object`类包含`NewType`类,而`NewType`又继承自`Object`。错误包括无限递归警告、内部堆限制、基类未定义等。通过使用头文件保护(`#ifndef`,`#define`,`#endif`)和前向声明(`class NewType;`)可以避免这些问题,但可能导致内联函数无法实现或类型未定义的错误。正确的做法是在需要完整类定义之前使用前向声明,而在实际使用时再包含完整的头文件。
932





