【问题标题】:Why do C++ constructors require default parameters in inheritance?为什么 C++ 构造函数在继承中需要默认参数?
【发布时间】:2020-01-23 19:47:09
【问题描述】:

当我没有在构造函数中提供任何默认参数时,编译器给我一个错误,说明我需要提供它们。我尝试了两种不同的情况:

  1. 为 x(x = 0) 提供默认参数,而对派生类中的名称不提供默认参数会导致错误
  2. 在派生类中为 name 而不是为 x 提供默认参数可以完美编译。 我不明白发生了什么,因为在基类中,是否提供了默认参数并没有真正改变任何东西。这仅特定于派生类吗?为什么为一个参数提供默认参数需要为另一个参数提供默认参数,或者这仅适用于继承的变量?
//Inheritance
#include<iostream>

using namespace std;
//why do constructors require default parameters

class Person
{
private:

public:
    string name;
    Person(string ref = " ")
        :name{ref}
    {
    }

    string Name()
    {
        return name;
    }
};

class Agent : public Person
{
private:

public:
    int kills;
    Agent(int x , string name = " " )   : kills{ x }, Person{name}
    {

    }
    void Detail()
    {
        cout << "Name : " << name << endl;
        cout << "Kills : " << kills << endl;
    }

};

int main()
{
    Agent test(24, "James bond");
    test.Detail();
    return 0;
}

感谢您的帮助

【问题讨论】:

  • 您能否展示一个无法编译的代码示例?
  • 看起来您的代码可以编译。你能给我们一个失败的代码的例子吗?你能edit把错误信息放到你的问题中吗?
  • 继承的类应该在成员初始化列表中的类成员之前。
  • @Christophe 但它在任何一种情况下都可以编译see

标签: c++ oop inheritance


【解决方案1】:

构造函数根本不需要默认参数。仅当您希望它们可用作默认构造函数时。

如果一个类没有默认构造函数,您仍然可以将其用作基类。您只需在派生类构造函数中自己调用正确的构造函数(在初始化列表中 - 您首先初始化基类,然后是您自己的成员)

例如

struct a { int m_i; a(int i) : m_i(i) {} };
struct b : a { int my_i; b() : a(42), my_i(666) {} };

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2015-07-09
    • 2016-03-24
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多