【问题标题】:Child class not a static member of parent子类不是父类的静态成员
【发布时间】:2015-04-12 15:12:35
【问题描述】:

我是 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’
...

我不明白为什么我从未定义过静态成员却说不是静态成员?

【问题讨论】:

    标签: c++ oop inheritance static


    【解决方案1】:

    您正试图在没有对象上下文的情况下访问类成员。该错误取决于您尝试将类属性初始化为静态的事实。

    这是错误的:

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

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

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

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

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

    【讨论】:

    • 谢谢...有没有办法只使用 Parent 类中的构造函数来做到这一点?提示说应该只有一个构造函数
    • 是的...您可以使用以下 sintax 从子类类构造函数调用父构造函数:Child::Child() : Creature(){ }。您只需将子类构造函数留空,它就会运行父构造函数中存在的代码。
    • 如果您尝试在构造函数中初始化变量,请使用构造函数初始化列表,而不是构造函数主体中的赋值语句。
    • @MattMcNabb,你是对的。那将是正确的方法。我要编辑我的答案。
    猜你喜欢
    • 2018-10-05
    • 2016-07-05
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多