【问题标题】:C++ inherited parent calling all constructor overloadsC++ 继承父调用所有构造函数重载
【发布时间】: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 不这样做。

标签: c++ multiple-inheritance


【解决方案1】:

这是错误的:

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;
    }
};

【讨论】:

  • 是的。真实故事:如果我刚刚观看了课程中的下一个视频,他也会经历同样的事情。
  • @JDillon522 我认为通过观看视频不可能学习 C++。我不想排除有一个好的视频教程的可能性,尽管它不会教你using namespace std;(而是解释why to avoid it)。我建议改用book
猜你喜欢
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2014-08-21
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多