简体   繁体   English

复制构造函数应该是私有的还是公共的

[英]Should copy constructor be private or public

I am writing an abstract class that will be a parent for several other classes. 我正在编写一个抽象类,它将成为其他几个类的父类。 I am thinking the copy constructor should be made private because you are using an abstract class and there is nothing to copy. 我认为复制构造函数应该是私有的,因为你使用的是抽象类,没有什么可以复制的。 However, I am not a 100% sure. 但是,我不是100%肯定。

Am I correct and if I am not why should it be public or protected? 我是否正确,如果我不是为什么要公开或受到保护?

The copy constructor should be private if you do not want objects of the class to be copied. 如果您不希望复制类的对象,则复制构造函数应该是私有的。 Otherwise, it should be public. 否则,它应该是公开的。

我认为protected是最好的选择:它决定对象是否可以复制到派生类,同时禁止在抽象类级别进行复制,防止可怕的对象切片

By making the copy constructor private you'll help prevent inadvertent object slicing, where you make a copy of a derived class but lose all the properties of that derived class. 通过将复制构造函数设置为私有,您将有助于防止无意中的对象切片,其中您创建派生类的副本但会丢失该派生类的所有属性。 The derived classes can make their own copy constructors that are public and do the right thing. 派生类可以创建自己的公共副本构造函数并做正确的事情。

There's one case where the copy constructor should be protected instead of private, when the abstract class has data members. 当抽象类具有数据成员时,有一种情况应该保护复制构造函数而不是私有。 This doesn't happen very often. 这种情况不会经常发生。 The base class can copy the base class members while the derived class copies its own members. 基类可以复制基类成员,而派生类复制自己的成员。

class AbstractBase
{
public:
    AbstractBase(const std::string &init) : wtf(init) {}
    virtual ~AbstractBase() {}
    void DoSomething() = 0;
protected:
    AbstractBase(const AbstractBase &r) : wtf(r.wtf) {}

    const std::string wtf;
};

class Derived : public AbstractBase
{
public:
    // ...
    Derived(const Derived &r) : AbstractBase(r), moredata(r.moredata) {}
private:
    int moredata;
};

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

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