我有一個Player類......他需要訪問PlayerStateFlying和PlayerStateHit類中的組件,以便我從他們身上繼承...誆騙自己與類繼承,需要一些指導
class PlayerStateFlying
{
// Includes a function that sets Player::currentState = something
}
class PlayerStateHit
{
// Includes a function that sets Player::currentState = something
}
class Player : public PlayerStateFlying,
public PlayerStateHit
{
public:
STATE currentState; // Needs to be accessed by the State classes
}
問題是,我的國家課程需要訪問玩家的某個屬性
我該如何解決這個問題?
--------- -----------編輯
所以它應該是這樣的? PS我不能完全得到它的工作
class IBaseStates
{
public:
STATE currentState;
}
class PlayerStateFlying : public IBaseStates
{
// Includes a function that sets IBaseStates::currentState = something
}
class PlayerStateHit : public IBaseStates
{
// Includes a function that sets IBaseStates::currentState = something
}
class Player : public IBaseStates
{
// Includes a function that checks what IBaseStates::currentState equals
}
這裏是我的困境的一個例子:
void Player::ChangeState(STATE state)
{
switch(state)
{
case FLYING:
currentState = FLYING;
break;
case HIT:
currentState = HIT;
break;
}
}
void Player::StateUpdate()
{
switch(currentState)
{
case FLYING:
PlayerStateFlying::Update();
currentTextureIndex = PlayerStateFlying::current;
break;
case HIT:
PlayerStateHit::Update();
currentTextureIndex = PlayerStateHit::current;
break;
}
}
void PlayerStateHit::Update()
{
...
currentState = FLYING;
index = 0;
...
}
http://en.wikipedia.org/wiki/Composition_over_inheritance –
谷歌「國家設計模式」的一些想法。 – godel9
爲什麼不直接在狀態類中添加'STATE currentState;'呢? – Proxy