我有两个班级单位和弓箭手。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 有点陌生,所以我想我可能会以错误的方式做这件事。如果有人能告诉我正确的方法,我会很高兴。