簡體   English   中英

不完整的類型/前向聲明/需要編譯理解

[英]Incomplete types/ forward declaration / compilation understanding needed

我有一個 Snake class,它有一個指向 Controller class object 的指針。該指針將在運行時分配一些新數據,即從 controller(例如 AIController)派生的 object。

我需要 Controller 個對象在構造時傳遞一個指向 Snake 的指針,這樣我就可以在 controller class 中調用 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();
}

蛇是這樣定義的:

class Controller;

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

   private:
      ...
      Controller* _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);

};

我不確定我嘗試使用指向 controller object 的指針以便我可以在運行時為 snake 分配不同的控制器是否正確,並且我知道我使用前向聲明時有些不正確。 我感謝最初的回復,並希望提供錯誤將使您能夠給我更多信息。 我將繼續嘗試解決問題,以便我能夠正確理解編譯過程,但與此同時,我非常感謝任何幫助!

將前向聲明放在 header 中,在包含 header 之前不需要。如果將它放在包含 header 之前,則每次包含標題之前都必須這樣做。

這里似乎缺少的另一件事是重復的包含保護(使用#ifndef 或使用#pragma once)。

將來最好將您遇到的實際錯誤(編譯器的錯誤消息)放在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM