2014-02-17 99 views
1

所以我在做一個遊戲,我有一個有哪個方向,玩家目前所面臨的,向上的枚舉,留下了一個Player類等不同類中的枚舉不兼容?

Player.h 
#include "Fireball.h" 
class Player 
{ 
    // Some stuff 
    Fireball fireballs; 
    void update(); 

    private: 
    enum direction {up, left, down, right, upLeft, upRight, downLeft, downRight} playerDir; 
}; 

我也有一個魔法類,我會從Fireball中獲取特定的法術。 Spell類的枚舉與Player類中的枚舉相同,因爲我希望能夠在更新咒語實例時將玩家的當前方向作爲參數傳遞,並將該咒語移動到方向。

Spell.h 
class Spell 
{ 
// Some stuff 

protected: 
    enum direction {up, left, down, right, upLeft, upRight, downLeft, downRight}; 
}; 

Fireball.h 
#include "Spell.h" 
class Fireball : public Spell 
{ 
public: 
    void updateFireballs(direction fireballDir); 
}; 

Player.cpp 
#include "Player.h" 

void Player::update() 
{ 
    fireballs.updateFireballs(playerDir); 
} 

當我嘗試,並通過playerDir作爲參數傳遞給updateFireballs功能,它抱怨說,它不能「球員::方向」轉化爲「拼寫::方向」。

如何將不同類中的枚舉作爲另一個類中的函數的參數傳遞?

+1

爲什麼要在兩個類中定義單獨的枚舉,尤其是如果要交替使用它們?在兩個類別之外有一個共同的定義會更有意義。 –

+0

即使你在類Player外面定義'direction',在裏面你仍然可以說'using direction = :: direction;'使'Player :: direction'成爲全局'direction'的同義詞。但也許你有類似「地圖」 - 方向通常屬於地圖。 – MSalters

回答

1

每個枚舉都是它自己的類型。當你在不同的類中定義兩個枚舉時,你定義了兩種類型。他們可能有相同的成員名稱,但他們是不相關的。

當你需要一個通用的枚舉定義一個。如果你發現這個枚舉會有名字衝突,你應該爲它定義一種「容器」。這可以是您的類PlayerSpell的名稱空間或基類。

0

不要在不相關的類中聲明兩次枚舉類。你可以在類之外定義它。如果你仍然需要它在拼寫類下,使其公開,其他類可以看到它。

class Spell 
{ 
public: 
    enum Direction {up, left, down, right, upLeft, upRight, downLeft, downRight}; 
}; 

class Fireball : public Spell 
{ 
public: 
    void updateFireballs(Spell::Direction fireballDir); 
}; 

class Player 
{ 
    Fireball fireballs; 
    void update() 
    { 
     fireballs.updateFireballs(playerDir); 
    } 
private: 
    Spell::Direction playerDir; 
}; 
相關問題