【发布时间】:2021-11-13 06:13:01
【问题描述】:
我正在处理this course on udemy,我对这个输出感到困惑。
Creature() 的默认父构造函数被调用,即使我通过子构造函数调用构造函数。过去 8 年我一直在 JavaScript 领域,所以我看到了一些古怪的东西,但我不确定我是如何意外完成的。
附:我知道这不是漂亮的代码,它是用于课程的。
#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 构造函数应该从成员初始化列表中调用 Creature 构造函数,而不是构造函数的主体。
-
另外,这实际上与多重继承没有任何关系。多重继承是指单个类从多个不同的基类继承,
Dragon不这样做。