2013-04-05 65 views
1

我目前正在製作一個遊戲,它利用狀態堆棧管理器來跟蹤所有不同的遊戲狀態,如主菜單。通過「this」作爲參數傳遞「沒有已知的轉換」

但是,我遇到了一個我似乎無法解決的問題。

這是狀態類,精簡到只包含有問題的代碼:

class StateManager; 

namespace first { 
namespace second { 

class State { 
    friend class StateManager; 
    protected: 
    /** 
    * Associates the state with the specified state manager instance. 
    * @param stateManager The instance to associate this state with 
    */ 
    void associateWithManager(StateManager *stateManager) { 
     mStateManager = stateManager; 
    } 
    private: 
    StateManager *mStateManager; 
}; 

} // second 
} // first 

以下是狀態管理,還剝了下來:

namespace first { 
namespace second { 

class StateManager { 
    public: 
    /** 
    * Adds a state to the stack. 
    * @param state The state to add 
    */ 
    State &add(State &state) { 
     state.associateWithManager(this); 
     return state; 
    } 
}; 

} // second 
} // first 

當我嘗試編譯此,我得到以下錯誤(行號有點偏離,因爲我有包括警衛等):

src/StateManager.cc: In member function 'State& StateManager::add(State&)': 
src/StateManager.cc:7:34: error: no matching function for call to 'State::associateWithManager(StateManager* const)' 
src/StateManager.cc:7:34: note: candidate is: 
In file included from ./include/StateManager.h:4:0, 
       from src/StateManager.cc:1: 
./include/State.h:29:10: note: void State::associateWithManager(StateManager*) 
./include/State.h:29:10: note: no known conversion for argument 1 from 'StateManager* const' to 'StateManager*' 

顯然,this指針被視爲const指針,儘管我在add方法中沒有使用const關鍵字。我不確定這裏到底發生了什麼。 this指針總是const?我很確定我以前用這種方式使用它,但沒有問題。

另外,我正在採取這種'正確'的方式嗎?或者,當談到讓國家瞭解經理時,是否有更好的解決方案?也許使用一個單身人士,但我並不是那麼喜歡的。

編輯:我現在認識到名稱空間之外的前向聲明是原因。我是否應該接受Mike的回答,因爲它幫助我得出了這個結論?或者我應該發佈自己的?

+1

代碼沒問題。你是否正在聲明'StateManager'? – ecatmur 2013-04-05 14:01:15

+0

[適用於我](http://ideone.com/JeS2bc)。這真的是唯一的錯誤嗎? – Angew 2013-04-05 14:01:49

+0

當我發佈這個問題時,我剝離了命名空間,但事實證明它實際上沒有它們進行編譯。我現在正在更新該問題,以顯示具有名稱空間等的代碼。 @ecatmur我確實向前聲明瞭StateManager。 – Merigrim 2013-04-05 14:17:36

回答

2

這是唯一的錯誤?當我編譯它,我第一次得到這個錯誤:

test.cpp:8:31: error: ‘StateManager’ has not been declared 

當聲明一個類是朋友,這個類必須已經聲明,否則該聲明將被忽略。因此,您需要在定義class State之前在周圍的名稱空間中聲明class StateManager;。隨着這一變化,你的代碼爲我編譯。

+0

您的答案幫助我找到了實際問題,請參閱我在問題中的編輯。非常感謝! =) – Merigrim 2013-04-05 14:35:26

+0

@Merigrim:如果你有更好的答案,那麼繼續併發布它,如果你喜歡。 – 2013-04-05 14:37:28

+0

雖然我可以撰寫回答指出具體問題並解決問題,但我認爲這樣做不一定更好。在這種情況下,即使您的答案如此接近,這是否正確? – Merigrim 2013-04-05 14:42:07

1

this指針不是StateManager *,它是一個StateManager * const

試着改變你的論點的常量性,以StateManager* const stateManager

,如果你不希望你的modifiy調用函數可以隨時拋棄的恆定性: state.associateWithManager(const_cast<StateManager*>(this));