2015-02-12 152 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