#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
最初のリンクで、 Space_C0wb0y は言う
「クローンメソッドはオブジェクトの実際のクラスのメソッドであるため、ディープコピーも作成できます。属するクラスのすべてのメンバーにアクセスできるため、問題はありません。」
ディープコピーがどのように発生するのかわかりません。上記のプログラムでは、浅いコピーすら行われていません。基本クラスが抽象クラスであっても機能する必要があります。ここでディープコピーを行うにはどうすればよいですか? 助けてください?