您当前的位置: 首页 >  c++

Jave.Lin

暂无认证

  • 1浏览

    0关注

    704博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ 类之间相互引用导致编译错误的问题

Jave.Lin 发布时间:2020-07-07 12:30:51 ,浏览量:1

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.hComponent.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++ 类互相引用问题?
关注
打赏
1664331872
查看更多评论
立即登录/注册

微信扫码登录

0.0622s