【发布时间】:2013-04-12 16:42:40
【问题描述】:
关于前向声明我有一点问题。我在一个文件中有以下课程
Robot.h
class Robot
{
public:
void moveForward()
private:
}
在 Robot.cpp 文件中实现
我有一个 UserReceiver.h 类,它定义了用户与机器人交互的接口等... 这个类用鼠标管理相机,我加载了 Robot 类的一个实例,以便可以与之交互
UserReceiver.h
class Robot;
class UserReceiver
{
public:
void LoadRobot(Robot* _robot) { robot = _robot; }
bool onEvent()
{
etc...
// Calling robot->moveForward() when clicking something
}
private:
Robot* robot;
}
如果需要,我可以提供完整的代码(我使用的 3D 引擎是 Irrlicht)。我的问题是如何转发声明与 Robot 类关联的方法?这个问题有没有好的设计模式?
我得到的错误是(在程序调用机器人的行->moveForward()):
error C2227: left of '->moveForward' must point to class/struct/union/generic type
非常感谢您的帮助
最好的问候
【问题讨论】:
-
你不能只在“UserReceiver.h”中包含“Robot.h”吗?
-
您不能在此处转发声明
Robot。您需要包含Robot.h。 -
感谢您的回答!实际上这只是我在一个大项目中提供的一个示例代码,并且在程序的每一层都使用了 EventReceiver,所以我决定在 EventReceiver.h 文件中使用前向声明以避免循环引用。如果这是唯一的解决方案,我会尝试使用 #include 而不是前向声明