子类不是父类的静态成员

时间:2015-02-12 02:07:13

标签: c++ oop inheritance static

我是C ++的新手并且遇到以下问题:

我有一个名为Creature的父类:

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 个答案:

答案 0 :(得分:1)

您正在尝试访问没有对象上下文的类成员。该错误依赖于您尝试初始化类属性的事实,因为它们是静态的。

这是错误的:

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

这是错误的,因为当我们谈论非静态属性时,它们必须与对象相关。您为属性提供默认值的方式,您不会将它们与任何对象相关联。

如果要为类属性提供默认值,请在构造函数中执行此操作,更具体地说,使用初始化列表(请查看here

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

...

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

每当调用构造函数(或任何非静态类方法)时,都会向其传递一个隐式对象引用(也称为指针this)。这样,使用此对象上下文始终会发生属性访问。

相关问题