0

我有一个 Snake 类,它有一个指向 Controller 类对象的指针。该指针将在运行时分配一些新数据,即从控制器(例如 AIController)派生的对象。

我需要在构造控制器对象时将指针传递给 Snake,以便我可以在控制器类中调用 Snake Getters/Setters。

在线上,在下面的代码片段中标记的 Snake 构造函数中,我收到以下错误:

In constructor 'Snake::Snake()':|
error: expected type-specifier before 'PlayerController'|
error: cannot convert 'int*' to 'Controller*' in assignment|
error: expected ';' before 'PlayerController'|

片段:

Snake::Snake() : _xVelocity(0), _yVelocity(0)
{
   _controller = new PlayerController(this);
   Initialise();
}

Snake 是这样定义的:

class Controller;

class Snake
{
   public:
      Snake();
      virtual ~Snake();
...

   private:
      ...
      Controller* _controller;


};

像这样的控制器:

#include "Snake.hpp"

class Controller
{
     public:
         Controller(Snake* s);
         ~Controller();


     protected:
         ...
         Snake* _s;
};

和 PlayerController 像这样:

#include "Controller.hpp"

class PlayerController : public prg::IKeyEvent, public Controller
{
     public:
         PlayerController(Snake* s);
         ~PlayerController();


     private:
         virtual bool onKey (const prg::IKeyEvent::KeyEvent& key);

};

我不确定我的尝试使用指向控制器对象的指针以便我可以在运行时分配不同的控制器是正确的,并且我知道我使用前向声明不太正确。我感谢最初的回复,并希望提供错误将使您能够给我更多信息。我将继续尝试清理问题,以便我可以正确理解编译过程,但同时我非常感谢任何帮助!

4

1 回答 1

0

Put the forward declarations in the header it is needed not before including the header. If you put it before including the header, you have to do it each time before you include the headers.

Another thing that seems to be missing here is the duplicate inclusion guards (either with #ifndef or with #pragma once).

In the future it is best to put here the actual errors you are encountering (the compiler's error messages).

于 2012-04-05T16:34:36.600 回答