2016-06-14 17 views
1

删除父在父类后孩子复制c'tor我:实现在CPP

Parent(const Parent& p) = delete; 

我想继承到子类,并在类中我想使用默认的复制c “做TOR:

Child(const Child& c) = default; 

但是我得到一个错误:"use of deleted function Parent(const Parent&)"

我为什么不能创建默认c'tor,是有办法解决? 谢谢!

+0

一个简单的解决方法是将父副本ctor声明为protected而不是删除。 – Dani

+5

听起来像我可疑的设计。如果不能复制父母,什么时候能够复制孩子? –

+1

为什么父母不能有抄送员有充足的理由吗?它是否包含无法复制的内容?如果没有,你不应该删除复制ctor。但是如果存在这样的原因,那么你可以写'Child(const Child&c):Parent(){}'。它会为复制的孩子构建一个新的父母,但它当然不会复制父母的数据。 – HolyBlackCat

回答

3

错误消息的原因是默认的拷贝构造函数调用基类的拷贝构造函数。由于被删除,编译器无法生成复制构造函数。解决方案是为派生类编写自己的拷贝构造函数,并且做任何你认为有意义的构造基类对象的“拷贝”。

+0

哎呀,我的坏。你完全正确。 – HolyBlackCat

2

派生类中会调用拷贝构造函数的基类的......

引用C++标准草案的相关部分的拷贝构造函数的默认实现... 部分这里转载:

[class.copy]

13. A copy/move constructor that is defaulted and not defined as deleted is implicitly defined if it is odr-used ([basic.def.odr]) or when it is explicitly defaulted after its first declaration.

而且

14. The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members. ....

所以,你最好打赌是手动定义基类的复制构造函数。但它通常不是一个好的设计来规避父类的复制构造函数。

class Parent{ 
public: 
    ..... 
    Parent(const Parent&) = delete; 
}; 


class Child : public Parent { 
public: 
    ..... 
    Child(const Child&) /* use c'tor init list here except for base class */ 
    { 
     ..... 
    } 
}; 
+0

Ctor初始化列表*必须*包含父项,但它必须调用与复制ctor不同的东西,不是吗? – HolyBlackCat

+0

@HolyBlackCat,是的..你是对的..例子[here](http://coliru.stacked-crooked.com/a/978bb0152950ec8f) – WhiZTiM