代码之家  ›  专栏  ›  技术社区  ›  Nav MetroidFan2002

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

  •  0
  • Nav MetroidFan2002  · 技术社区  · 15 年前
    #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
    

    运行时:

    Called constructor and allocated id
    Something initialized. j=20
    DERIVED id=10
    DERIVED id=0
    

    我的问题与 this , this this

    在第一个链接中,Space_C0wb0y说

    “因为克隆方法是 同时创建深拷贝。它可以访问 它所属班级的所有成员 所以没有问题。”

    我不明白怎么会发生深度复制。在上面的程序中,甚至没有一个浅拷贝发生。 即使基类是抽象类,我也需要它工作

    1 回复  |  直到 9 年前
        1
  •  5
  •   jv42    15 年前

    好吧,你的复制构造函数什么也不做,所以你的克隆方法在复制的时候什么也不做。

    请参阅线条 Derived(const Derived&) {}

    编辑:如果添加要通过赋值复制派生的所有成员的代码,它将成为一个浅拷贝。如果您还复制(通过创建一个新实例)某个对象的实例,它将成为一个深层副本。