隐式删除了复制构造函数,因为默认定义不正确

Nic*_*mer 8 c++ clone copy-constructor private-constructor

我有一个类A(来自我无法控制的库),有一个私有拷贝构造函数和一个clone方法,以及一个B派生自的类A.我想实现cloneB为好.

天真的做法

#include <memory>

class A { // I have no control here
  public:
    A(int a) {};

    std::shared_ptr<A>
      clone() const
      {
        return std::shared_ptr<A>(new A(*this));
      }

  private:
    A(const A & a) {};
};

class B: public A {
  public:
    B(int data, int extraData):
      A(data),
      extraData_(extraData)
    {
    }

    std::shared_ptr<B>
    clone() const
    {
      return std::shared_ptr<B>(new B(*this));
    }

  private:
    int extraData_;
};

int main() {
  A a(1);
}
Run Code Online (Sandbox Code Playgroud)

但是,失败了,因为复制构造函数A是私有的:

main.cpp: In member function ‘std::shared_ptr<B> B::clone() const’:
main.cpp:27:42: error: use of deleted function ‘B::B(const B&)’
     return std::shared_ptr<B>(new B(*this));
                                      ^
main.cpp:17:7: note: ‘B::B(const B&)’ is implicitly deleted because the default definition would be ill-formed:
 class B: public A {
       ^
main.cpp:14:5: error: ‘A::A(const A&)’ is private
     A(const A & a) {};
     ^
main.cpp:17:7: error: within this context
 class B: public A {
Run Code Online (Sandbox Code Playgroud)

可能有一种方法可以使用A::clone()for B::clone(),但我不确定这是如何工作的.任何提示?

Naw*_*waz 2

您需要创建Aprotected 的复制构造函数,以便派生类可以使用它:

protected:
    A(const A & a) { /*...*/ }
Run Code Online (Sandbox Code Playgroud)

希望有帮助。