c++ - 基类构造函数参数与派生类构造函数之间的关系

标签 c++ inheritance constructor

我无法理解这句话:“如果基类有带参数的构造函数,那么派生类必须有构造函数并将参数传递给基类构造函数。” 如果可以,请使用一些程序。

最佳答案

如果您有一个名为 Animal 的基类和一个名为 Dog 的派生类。您需要在 Dog 的构造函数中调用 Animal 的构造函数来初始化继承的成员变量。一个非常基本的示例如下所示:

class Animal
{
int num_legs;
public:
Animal(int legs): num_legs(legs){}
};

class Dog: public Animal
{
public:
// now we send the number of legs to the Base class
Dog(int legs): Animal(legs) {}
};

如果您依赖 Dog 的默认构造函数,在这种情况下,您最终会得到一个未初始化的腿变量。

希望对您有所帮助。

关于c++ - 基类构造函数参数与派生类构造函数之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421667/

相关文章:

javascript - JS Array.prototype.filter with Array 扩展类构造函数调用

javascript - 从错误中恢复

javascript - 使用 JavaScript 函数添加动态 HTML 内容

c# - 为什么 C# 构造函数不能推断类型?

c++ - 模板外部(与外部模板相比)

c++ - 调试到 MFC header 代码不适用于 Visual Studio 2019

c++ - 是否可以在 C++ 中推断类型转换为模板化类型?

c++ - 尝试编译包含 Root (Cern) 参数的 C++ 代码

javascript - 为什么 Javascript 默认不支持继承?

C++继承与LNK2019