c++ - 构造函数链接不使用类成员的默认值?
问题描述
我有两个班级单位和弓箭手。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 有点陌生,所以我想我可能会以错误的方式做这件事。如果有人能告诉我正确的方法,我会很高兴。
解决方案
这是一个非首发
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){};
};
推荐阅读
- amazon-web-services - 在解码 JWT 时,从 AWS 机密管理器中检索机密会导致问题
- expo - 使用 expo branch.io SDK 和广告合作伙伴链接安装归因
- admin - 为什么我不能成为 Telegram 的管理员?
- react-navigation - 在navigation.goback() 之后需要返回吗?
- c# - 当我们有支持 OOP 概念的类和接口时,为什么 C# 支持结构
- java - MetricRegistry 的可序列化类中的非瞬态不可序列化实例字段
- python - 一种将函数循环到自身的pythonic方法
- objective-c - XCode - 如何在共享扩展中包含 React Native 库?
- matlab - 为什么如果 `t(n)==0.06`,在我的命令窗口中无法显示 0.06?
- ios - 如何将四舍五入的整数显示到标签?