[英]Is this Polymorphism and is this bad practice?
我正在為我的游戲設置一個 State 系統。
class State
{
protected:
enum State_
{
STATE_INTRO,
STATE_GAME,
STATE_PAUSE,
STATE_CUTSCENE,
};
public:
State();
virtual void run(State_) = 0;
virtual ~State(); // virtual destructor cus we will be inheriting this class
};
然后我繼承了代表每個 state 的類
class IntroState : public State
{
public:
void run(State_ STATE);
};
我希望run
function 根據游戲所在的 state 具有不同的功能,這樣實現是不是不好的做法:
void IntroState::run(State_ STATE)
{
if (STATE == STATE_INTRO)
{
// load the intro
}
}
我不確定該怎么做,謝謝(請記住,我只是在學習狀態,所以我可能會完全離開這里)
我認為您的情況不需要多態性,因為您的應用程序中只有一個State
class(如果我錯了請糾正我)。
你運行 function 看起來像這樣:
void run(State_ state)
{
switch (state)
{
case STATE_INTRO:
doIntro();
case STATE_BLAH:
doBlah();
// fill all you states...
}
}
void doIntro()
{
// do something for the intro
}
void doBlah()
{
// do something for blah
}
現在,如果你真的想變得有趣並刪除switch
語句:
class State
{
private:
void doA() {}
void doB() {}
enum State_
{
A = 0,
B,
END_
};
std::function<void(void)> functions[END_];
public:
State()
{
functions[A] = std::bind(&State::doA, this);
functions[B] = std::bind(&State::doB, this);
}
void run(State_ state)
{
functions[state]();
}
};
為了擴展我的評論,這是一種可能的方法(感謝改進):
class Game {
//... Initialize all State-derived classes in constructor and put them in states (not shown)
vector<unique_ptr>> states;
State_ currentState {STATE_INTRO};
State_ nextState {STATE_INTRO};
public:
void setNextState(State_ state ) {nextState = state;}
void Play() {
for(;;) { //endless loop
if (!states[currentState]->run()) return;//stopping when run returns false
currentState = nextState;
}
}
};
run
看起來像這樣:
class IntroState : public State {
//...
void run(Game& game) {
// do stuff
game.setNextState(STATE_GAME);
return true;
}
};
當然,你需要弄清楚include順序,你需要在State.hpp
中轉發聲明Game
(這里的代碼只是展示了中心思想)。 此外, run
和Play
的實現當然應該放在單獨的.cpp 文件中(這里沒有這樣做,所以這個例子不會太長)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.