首页 > 解决方案 > 编译器坚持引用不存在的构造函数

问题描述

我正在尝试做的是shadow基于Player. 我有两个 Shadow 类构造函数:一个接受一个playerboss参数,一个只接受一个播放器参数。如果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() 构造函数。帮助?

标签: c++

解决方案


编码

Shadow(player); // error here

不做你认为它做的事。它等效于以下代码:

Shadow player;

也就是说:您正在尝试声明player类的本地对象Shadow并默认构造它。由于缺少构造函数,这失败了。

你想调用一个委托构造函数。为此,您需要使用初始化列表

Shadow::Shadow(const Player & player, bool boss) : Shadow(player) {
    if (boss) {
        // boost stats
    }
}

推荐阅读