简体   繁体   English

C ++ 11构造函数继承和没有参数的构造函数

[英]C++11 constructor inheritance and constructors with no parameters

In this piece of code, why is A's constructor with no parameters not inherited? 在这段代码中,为什么A的构造函数没有参数没有被继承? Is there a special rule that prevents inheriting constructors with no parameters? 是否有一个特殊规则阻止继承没有参数的构造函数?

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 gives this error, and g++ -std=c++11 gives a substantially similar error message: 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 *) {}

The relevant information is in 12.9 [class.inhctor] paragraph 3 (the highlighting is added): 相关信息见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. 对于除了没有参数的构造函数或具有单个参数的复制/移动构造函数之外的候选继承构造函数集中的每个非模板构造函数 ,构造函数隐式声明具有相同的构造函数特征,除非存在用户声明的构造函数在使用声明出现的完整类中的相同签名。 [...] [...]

That is, default constructor are not inherited unless they have a [defaulted] argument. 也就是说,默认构造函数不会被继承,除非它们具有[defaultaulited]参数。 If they have a default argument they are inherited but without the defaulted argument as is pointed out by a node on the same paragraph: 如果它们有一个默认参数,则它们是继承的,但没有默认参数,如同一段落上的节点所指出的:

Note: Default arguments are not inherited. 注意:不继承默认参数。 [...] [...]

Basically, that says that default constructors are not inherited. 基本上,这表示默认构造函数不是继承的。

B中没有没有参数的构造函数,试试

B() : A(){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM