在C++ 11中,继承构造函数是什么意思?如果这是我的想法(基类构造函数在派生类的范围内),那么它对我的代码有什么影响?这种功能有哪些应用?

最佳答案

继承构造函数就是这样。派生类可以从其基类隐式继承构造函数。

语法如下:

struct B
{
    B(int); // normal constructor 1
    B(string); // normal constructor 2
};

struct D : B
{
    using B::B; // inherit constructors from B
};

因此,D现在隐式定义了以下构造函数:
D::D(int); // inherited
D::D(string); // inherited

这些继承的构造函数默认构造Ds成员。

好像构造函数定义如下:
D::D(int x) : B(x) {}
D::D(string s) : B(s) {}

该功能没有什么特别的。这只是保存键入样板代码的捷径。

这是血腥的细节:

07-24 09:45
查看更多