【问题标题】:C++11 constructor inheritance and constructors with no parametersC++11构造函数继承和无参数构造函数
【发布时间】:2013-12-24 12:14:49
【问题描述】:

在这段代码中,为什么没有继承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 *) {}

【问题讨论】:

    标签: c++ inheritance c++11 constructor


    【解决方案1】:

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

    对于候选继承构造函数集合中的每个非模板构造函数除了没有参数的构造函数或具有单个参数的复制/移动构造函数,构造函数被隐式声明为相同的构造函数特征,除非在出现 using 声明的完整类中存在具有相同签名的用户声明构造函数。 [...]

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

    注意:默认参数不会被继承。 [...]

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

    【讨论】:

      【解决方案2】:

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

      B() : A(){}
      

      【讨论】:

      • 问题是为什么A 的默认构造函数不是通过语句using A::A 继承的。这是一个明显但无关紧要的解决方案。
      • 我不知道你从哪里使用 A::A,或者它是否应该像我想的那样工作,但是在 C++ 中没有禁止继承没有参数的构造函数。甚至派生类的默认构造函数也会这样做。
      • using A::A 来自 OPs 代码。如果您阅读了上面的答案,它就说明了问题。
      猜你喜欢
      • 1970-01-01
      • 2013-05-21
      • 2012-11-14
      • 2016-03-24
      • 2017-08-05
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多