rma*_*a31 5 c++ inheritance constructor
在 C++ 中,构造函数不是继承的。然而,我使用 clang12 有一个奇怪的发现。它可以使用 C++17 编译,尽管它不应该编译。如果我使用 C++11 或 C++14,它不会按我的预期进行编译。
#include <iostream>
class Parent{
int x_;
public:
//Parent() = default;
Parent(int const &x) : x_{x} {}
void SayX(){ std::cout << x_ << std::endl; }
};
class Child : public Parent{
// works with C++17 ff.
};
int main(){
Child c {2};
c.SayX();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
--> 使用 C++17 ff. 输出 2,不能使用 C++11、14 进行编译
您没有看到继承的构造函数(您是对的,这些是通过选择加入的using),而是聚合初始化,它确实已在 C++17 中扩展以覆盖基类。来自cppreference(强调我的):
聚合的元素是:
[...]
对于类,先是按声明顺序排列的直接基类,然后是按声明顺序排列的既不是匿名位域也不是匿名联合成员的直接非静态数据成员。(自 C++17 起)
因此,从Child c {2};复制构造其子对象。Parent2