我目前正在製作一個遊戲,它利用狀態堆棧管理器來跟蹤所有不同的遊戲狀態,如主菜單。通過「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的回答,因爲它幫助我得出了這個結論?或者我應該發佈自己的?
代碼沒問題。你是否正在聲明'StateManager'? – ecatmur 2013-04-05 14:01:15
[適用於我](http://ideone.com/JeS2bc)。這真的是唯一的錯誤嗎? – Angew 2013-04-05 14:01:49
當我發佈這個問題時,我剝離了命名空間,但事實證明它實際上沒有它們進行編譯。我現在正在更新該問題,以顯示具有名稱空間等的代碼。 @ecatmur我確實向前聲明瞭StateManager。 – Merigrim 2013-04-05 14:17:36