c++ - 编译器坚持引用不存在的构造函数
问题描述
我正在尝试做的是shadow
基于Player
. 我有两个 Shadow 类构造函数:一个接受一个player
和boss
参数,一个只接受一个播放器参数。如果boss
为真,shadow
将获得更好的统计数据。
我的代码:
class Player
{
public:
typedef size_t pos;
private:
mutable pos lp;
mutable pos sp;
mutable pos exp;
mutable pos lvl;
std::string name;
public:
explicit Player(std::istream & is){is >> lp >> sp >> exp >> lvl >> name;}
Player(const std::string & aName, pos aLp = 100, pos aSp = 100, pos aExp = 1, pos aLvl = 1):
name(aName), lp(aLp), sp(aSp), exp(aExp), lvl(aLvl) {}
};
class Shadow
{
public:
using pos = size_t;
private:
pos lvl;
pos lp;
bool boss;
public:
static const pos sp = ULLONG_MAX;
explicit Shadow(const Player & player): lvl(player.lvl + 5), lp(player.lp + 50) {}
Shadow(const Player & player, bool boss);
pos showLvl() const {return this->lvl;}
pos showLp() const {return this->lp;}
};
Shadow::Shadow(const Player & player, bool boss)
{
if(!boss)
Shadow(player); // error here
else
{
lvl = player.lvl + 10;
lp = player.lp + 150;
}
int main()
{Player Minato("Minato");
Player Junpei("Junpei");
Player Yukari("Yukari");
Player Akihiko("Akihiko");
Shadow blockGuard(Minato, false);
return 0;}
我得到的错误:“没有匹配函数调用'Shadow::Shadow()'。”
问题是没有 Shadow::Shadow() 构造函数。帮助?
解决方案
编码
Shadow(player); // error here
不做你认为它做的事。它等效于以下代码:
Shadow player;
也就是说:您正在尝试声明player
类的本地对象Shadow
并默认构造它。由于缺少构造函数,这失败了。
你想调用一个委托构造函数。为此,您需要使用初始化列表:
Shadow::Shadow(const Player & player, bool boss) : Shadow(player) {
if (boss) {
// boost stats
}
}
推荐阅读
- sails.js - Sails.js 中的 Service 和 Helper 有什么区别?
- html - 从 Outlook 打开电子邮件时 HTML 文本显示两次
- javascript - 页面重新加载后如何隐藏和显示按钮
- c#-4.0 - 对象到带有列表和字典的元组 c#
- jquery - 使用对象 jquery 或 javascript 内连接两个数组
- python - Pandas - read_sql_query 填充列名
- javascript - 如何使用javascript根据其值更改数字的颜色并做出反应?
- html - 将超大图像放入父容器中
- flutter - 输入'未来
' 不是类型 'Future 的子类型 ' - python - Statsmodels ACF置信区间不匹配 - Python