C++继承父调用所有构造函数重载

C++ inherited parent calling all constructor overloads

我正在研究 this course on udemy,但我对这个输出感到困惑。

即使我通过子构造函数调用构造函数,也会调用 Creature() 的默认父构造函数。在过去的 8 年里,我一直在 JavaScript 土地上,所以我看到了一些古怪的东西,但我不确定我是如何不小心把它拉下来的。

P.S。我知道这不是漂亮的代码,它是课程的。

#include <iostream>;
#include <string>;

using namespace std;

class Creature
{
public:
    Creature();
    Creature(string name, float health);

    string Name;
    float Health;
};

class Dragon:public Creature
{
public:
    Dragon();
    Dragon(string name, float health);
};

int main()
{
    Dragon dragon2("Smaug", 100.f);
    cout << "The Dragon's name should be Smaug: " << dragon2.Name << endl;
    
    return 0;
}
 
Creature::Creature(string name, float health)
{
    Name = name;
    Health = health;
    cout << "Creature constructor WITH arguments" << endl;
};

Creature::Creature() 
    : Name("UNAMED"), Health(100.f)
{
    cout << "Creature constructor with NO arguments" << endl;
}

Dragon::Dragon(string name, float health)
{
    Creature(name, health);
    cout << "Dragon constructor WITH arguments" << endl;
}

Dragon::Dragon()
{
    cout << "Dragon Constructor with NO arguments" << endl;
}

输出:

Creature constructor with NO arguments
Creature constructor WITH arguments
Dragon constructor WITH arguments
The Dragon's name should be Smaug: UNAMED

我理解(大概)为什么以及如何调用默认构造函数,但我希望输出是:

Creature constructor WITH arguments
Dragon constructor WITH arguments
The Dragon's name should be Smaug: Smaug

这是错误的:

Dragon::Dragon(string name, float health)
{
    Creature(name, health);
    cout << "Dragon constructor WITH arguments" << endl;
}

嗯,它在语法上是正确的,但它并没有按照您的想法去做。 Creature(name,health); 调用 Creature 的构造函数来创建一个临时文件,它一直存在到该行的末尾。您会看到默认构造函数被调用,因为您没有为正在构造的 Dragon 调用 Creature 构造函数,因此 DragonCreature 部分是默认构造的。

调用基础构造函数:

class Dragon : public Creature
{
public:
    Dragon();
    Dragon(string name, float health) : Creature(name,health) {
        cout << "Dragon constructor WITH arguments" << endl;
    }
};