继承构造函数和默认构造函数

时间:2015-12-17 13:57:56

标签: c++ inheritance constructor default-constructor

我正在阅读Inheriting constructors here上的文档。有一个例子:

struct B1 {
    B1(int);
};
struct D1 : B1 {
    using B1::B1;
// The set of inherited constructors is 
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)

// D1 has the following constructors:
// 1. D1()
// 2. D1(const D1&) 
// 3. D1(D1&&)
// 4. D1(int) <- inherited
};

所以它写得很清楚D1 has the following constructors: D1(),即默认构造函数。但是当我试图创建一个对象时:

D1 d;

我有一个错误use of deleted function 'D1::D1()'。这是文档中的错误还是我误解了什么?

我用c ++ 14尝试了gcc。

2 个答案:

答案 0 :(得分:1)

请考虑以下代码:

struct B1                                                                                                                                                                                                
{
    B1(int){}
};

struct D1 : B1 {
    using B1::B1;
};


struct E
{
    E(){}
};


struct F
{
    F(int){}
};

如果你试着写

E e;

它会很好,但是

F f;

会失败。通过声明一个int的ctor,您已经有效地删除了默认的ctor。

您的问题代码遵循相同的原则。将B1 ctor拉入D1后,您已有效删除了其默认代码。

答案 1 :(得分:-2)

更进一步说,它说它没有默认的构造函数

D1 e; //错误:D1没有默认构造函数