创建不使用虚拟基类的对象的克隆

Nav*_*Nav 0 c++ virtual deep-copy shallow-copy

#include<iostream>
using namespace std;

class Something
{
  public:
  int j;
  Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};

class Base
{
  private:
    Base(const Base&) {}
  public:
    Base() {}
    virtual Base *clone() { return new Base(*this); }
    virtual void ID() { cout<<"BASE"<<endl; }
};

class Derived : public Base
{
  private:
    int id;
    Something *s;
    Derived(const Derived&) {}
  public:
    Derived():id(10) {cout<<"Called constructor and allocated id"<<endl;s=new Something();}
    ~Derived() {delete s;}
    virtual Base *clone() { return new Derived(*this); }
    virtual void ID() { cout<<"DERIVED id="<<id<<endl; }
    void assignID(int i) {id=i;}
};


int main()
{
        Base* b=new Derived();
        b->ID();
        Base* c=b->clone();
        c->ID();
}//main
Run Code Online (Sandbox Code Playgroud)

在跑步时:

Called constructor and allocated id
Something initialized. j=20
DERIVED id=10
DERIVED id=0
Run Code Online (Sandbox Code Playgroud)

我的问题是有关这个,这个这个职位.

在第一个链接中,Space_C0wb0y说

"由于clone-method是对象的实际类的一种方法,它也可以创建一个深层拷贝.它可以访问它所属的类的所有成员,所以没有问题."

我不明白深层复制是如何发生的.在上面的程序中,甚至没有发生浅拷贝.即使Base类是一个抽象类,我也需要它才能工作.我怎么能在这里做一个深层复制?请帮忙?

jv4*_*v42 5

好吧,你的拷贝构造函数什么都不做,所以你的克隆方法在复制方面没有任何作用.

见行 Derived(const Derived&) {}

编辑:如果您添加代码以通过分配Derived的所有成员进行复制,它将成为浅层副本.如果您还复制(通过创建新实例)您的Something实例,它将成为深层副本.