Jer*_*Sci 2 c++ oop inheritance
当我没有在构造函数中提供任何默认参数时,编译器给了我一个错误,说明我需要提供它们。我尝试了两种不同的情况:
//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;
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助
构造函数根本不需要默认参数。仅当您希望它们可用作默认构造函数时。
如果一个类没有默认构造函数,你仍然可以将它用作基类。您只需要在派生类构造函数中自己调用正确的构造函数(在初始化列表中 - 首先初始化基类,然后初始化您自己的成员)
例如
struct a { int m_i; a(int i) : m_i(i) {} };
struct b : a { int my_i; b() : a(42), my_i(666) {} };
Run Code Online (Sandbox Code Playgroud)