首页 > 解决方案 > 构造函数链接不使用类成员的默认值?

问题描述

我有两个班级单位和弓箭手。Archer 继承自 unit。我尝试使用构造函数链接来设置基类的统计信息,但如果我使用以下代码,统计信息似乎设置为零:

#include<iostream>

using namespace std;

class Unit{
    int damage = 0;
    int curHp = 0;
    int maxHp = 1;
    int range = 0;
    int cost = 0;

public:
    Unit(int _damage,int _maxHp,int _range,
         int _cost){
        damage = _damage;
        curHp = maxHp = _maxHp;
        range = _range;
        cost = _cost;
    }

    int getCost(){
        return cost;
    }
};

class Archer: public Unit{
    int damage = 25;
    int range = 50;
    int maxHp = 100;
    int cost = 150;
    int stepSize = 25;
    int returnedCoins = 0;
public:
    Archer():Unit(damage,maxHp,range,
                  cost){};
};

int main()
{
    Unit *curUnit =  new Archer();
    cout<< curUnit->getCost()<<endl;;
}

输出为 0。如果我用一个值而不是使用成本(例如 25)调用 Unit 的构造函数,我会得到我使用的值。由于某种原因,我在弓箭手类中设置的基本值根本没有被使用。

另外,我对 OOP 有点陌生,所以我想我可能会以错误的方式做这件事。如果有人能告诉我正确的方法,我会很高兴。

标签: c++oopinheritanceconstructorconstructor-chaining

解决方案


这是一个非首发

class Archer: public Unit{
    int damage = 25;
    int range = 50;
    int maxHp = 100;
    int cost = 150;
    int stepSize = 25;
    int returnedCoins = 0;
public:
    Archer():Unit(damage,maxHp,range,
                  cost){};
};

基类在类成员之前初始化。说到这,你无缘无故地复制了相同的成员。只需将它们作为参数传递:

class Archer: public Unit{
    int stepSize = 25;
    int returnedCoins = 0;
public:
    Archer():Unit(25,100,50,
                  150){};
};

如果您的目标只是为这些值赋予有意义的名称,则可以将它们设为静态类常量:

class Archer: public Unit{
    static constexpr int damage = 25;
    static constexpr int range = 50;
    static constexpr int maxHp = 100;
    static constexpr int cost = 150;

    int stepSize = 25;
    int returnedCoins = 0;
public:
    Archer():Unit(damage,maxHp,range,
                  cost){};
};

推荐阅读