gpt4 book ai didi

C++11构造函数继承和无参数构造函数

转载 作者:可可西里 更新时间:2023-11-01 17:51:04 26 4
gpt4 key购买 nike

这段代码中,为什么A的无参构造函数没有被继承呢?是否有特殊规则阻止继承不带参数的构造函数?

struct A {
A(void *) {}
A() {}
};

class B : public A {
public:
using A::A;
B(int x) {}
};

void f() {
B b(1);
B b2(nullptr);
B b3; // error
}

clang++ -std=c++11 给出了这个错误,而 g++ -std=c++11 给出了一个基本相似的错误消息:

td.cpp:15:7: error: no matching constructor for initialization of 'B'
B b3; // error
^
td.cpp:9:5: note: candidate constructor not viable: requires single argument 'x', but no arguments
were provided
B(int x) {}
^
td.cpp:8:14: note: candidate constructor (inherited) not viable: requires 1 argument, but 0 were
provided
using A::A;
^
td.cpp:2:5: note: inherited from here
A(void *) {}

最佳答案

相关信息在12.9 [class.inhctor]第3段(加亮):

For each non-template constructor in the candidate set of inherited constructors other than a constructor having no parameters or a copy/move constructor having a single parameter, a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears. [...]

也就是说,默认构造函数不会被继承,除非它们有一个 [defaulted] 参数。如果它们有默认参数,它们将被继承,但没有默认参数,正如同一段落上的节点所指出的那样:

Note: Default arguments are not inherited. [...]

基本上,这表示默认构造函数不是继承的。

关于C++11构造函数继承和无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com