2015-02-12 156 views
1

的靜態成員,我是一個新手,C++和具有以下問題:兒童類沒有父

我有一個父類,稱爲怪物:像這樣

class Creature 
{ 
public: 
    bool isActive; 
    std::string name; 
    int attackNumOfDice, attackNumOfSides, 
       defenseNumOfDice, defenseNumOfSides; 
    int armor, strength; 

    Creature(); 
    //two virtual functions determine the damage points 
    virtual int attack(); 
    virtual int defend(); 
    void halveAttackDice(); 
    void setStrength(int toSet); 
    void setStatus(bool activity); 

}; 

和5子類:

.h文件中:

class Child : public Creature 
{ 
int attack(); 
int defend(); 
} 

實現文件:

int Child::isActive = true; 
    std::string Child::name = ""; 
    int Child::attackNumOfDice = 2; 
    ... 

    int Child::attack() 
{ 
... 
} 
    intChild::defend() 
{ 
...} 

然而,當我嘗試編譯這樣我得到所有5個子類相同的錯誤:

child.cpp:6: error: ‘bool Child::isActive’ is not a static member of ‘class Child’ 
child.cpp:7: error: ‘std::string Child::name’ is not a static member of ‘class Child’ 
child.cpp:8: error: ‘int Child::attackNumOfDice’ is not a static member of ‘class Child’ 
... 

我不明白爲什麼說不是一個靜態的成員時,我從來沒有一個定義?

回答

1

您試圖訪問沒有對象上下文的類成員。該錯誤依賴於您試圖初始化類屬性的事實,因爲它們是靜態的。

這是錯誤的:

int Child::isActive = true; 
std::string Child::name = ""; 
int Child::attackNumOfDice = 2; 

這是錯誤的,因爲當我們談論非靜態的屬性,它們必須與對象相關的。你給屬性賦予默認值的方式,你並沒有將它們與任何對象相關聯。

如果你想爲你的類屬性的默認值,這樣做的一個構造函數中,更特別是使用初始化列表(取here看看)

Child::Child() : Creature(){ 
    ... 
} 

... 

Creature::Creature() : isActive(false), name(""){ 
    ... 
} 

每當調用構造函數(或任何非靜態類方法),隱式對象引用(也稱爲指針this)被傳遞給它。這樣,屬性訪問總是使用這個對象上下文來進行。

+0

謝謝...有沒有辦法只使用父類中的構造函數呢?提示說應該只有一個構造函數 – 2015-02-12 02:18:16

+0

yes ......你可以使用這個sintax:Child :: Child():Creature(){}從子類的構造函數調用父構造函數。您只需將您的子類構造函數留空,並且它將運行父構造函數中存在的代碼。 – 2015-02-12 02:24:13

+1

如果您嘗試在構造函數中初始化變量,則使用構造函數體中的構造函數初始化程序列表,即賦值語句的intead。 – 2015-02-12 03:26:21