C++ 构造函数继承?

huangapple go评论66阅读模式
英文:

C++ constructor inherited?

问题

在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;
}

--> 在C++17下输出2,而在C++11、14下无法编译。

英文:

In C++ constructors are not inherited.
However, I have this strange finding using clang12.
It compiles with C++17 following although it shouldn't.
If I use C++11 or C++14 it doesn't compile as I expected.

#include &lt;iostream&gt;

class Parent{
    int x_;
public:
    //Parent() = default;
    Parent(int const &amp;x) : x_{x} {}
    void SayX(){ std::cout &lt;&lt; x_ &lt;&lt; std::endl; }
};
class Child : public Parent{
    // works with C++17 ff.
};
int main(){
    Child c {2};
    c.SayX();
    return 0;
}

--> Outputs 2 with C++17 ff., doesn't compile with C++11, 14

答案1

得分: 7

你没有看到一个继承的构造函数(你说得对,这些通过 using 是可选的),但是聚合初始化确实在C++17中得到了扩展,包括基类。根据cppreference(重点在于):

聚合的元素包括:

  • [...]

  • 对于类,声明顺序的直接基类,后跟声明顺序的直接非静态数据成员,既不是匿名位域,也不是匿名联合的成员。 <sub>(自C++17起)</sub>

所以 Child c {2};2 复制构造其 Parent 子对象。

英文:

You're not seeing an inherited constructor (you are right that these are opt-in through using), but aggregate initialization, which has indeed been extended in C++17 to cover base classes. From cppreference (emphasis mine):

> The elements of an aggregate are:
>
> * [...]
>
> * for a class, the direct base classes in declaration order, followed by the direct non-static data members that are neither anonymous bit-fields nor members of an anonymous union, in declaration order. <sub>(since C++17)</sub>

So Child c {2}; copy-constructs its Parent subobject from 2.

huangapple
  • 本文由 发表于 2023年3月31日 16:31:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定