C++ 的编译器提示报错 XXXX 定义不存在
导致这个原因是因为我在写两个类的时候,他们有相互引用,而这种引用关系,在某些功能是无法避免的,以前用C#的时候是不会有这种问题,编译器帮我们处理了很多这些问题,但在C++中就需要自己处理了。
错误示例如下:先有一个头文件GameObject.h
// jave.lin
// GameObject.h
#ifndef _GAMEOBJECT__H_
#define _GAMEOBJECT__H_
#include"Component.h"
class GameObject {
public:
Component* getComponents();
};
#endif
再是有一个头文件 Component.h
// jave.lin
// Component.h
#ifndef _COMPONENT__H_
#define _COMPONENT__H_
#include"GameObject.h"
class Component {
public:
GameObject* getOwner();
};
#endif
这样就会出现各种编译错误(因为我的工程实际有比较多测类定义,如果新建一个工程专门去查看这类编译错误,可能会出现:GameObject.h 文件中出现,“找不到 Component 类定义” 之类的)
错误原因出现错误的原因就是因为 GameObject、Component 之间有相互类型引用。
如果你代码中先使用 #include"GameObject.h"
的,那么这时候,GameObject 类中是找不到 Component 的定义的,因为在此之前是找不到 Component 的任何定义代码。
如果先试用的是 #include Component.h
的,那么 Component 类中同样是找不到 GameObject 的定义。
可以使用 C++ 的 前置声明 / forward declaration
正确示例我们将 GameObject.h
和 Component.h
文件内容都合并到一个文件: GameObject_etc.h
// jave.lin
// GameObject_etc.h
#ifndef _GAMEOBJECT_ETC__H_
#define _GAMEOBJECT_ETC__H_
class Component; // forward declaration
class GameObject {
public:
Component* getComponents();
};
class Component {
public:
GameObject* getOwner();
};
#endif
所以只能将有相互引用的类定义都放一个文件,然后使用 前置声明 / forward declaration
References- c++ 类互相引用问题?