#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 说
“由于clone-method是对象实际类的方法,它也可以创建一个深拷贝。它可以访问它所属的类的所有成员,所以没有问题。”
我不明白深拷贝是如何发生的。在上面的程序中,甚至没有发生浅拷贝。即使 Base 类是抽象类,我也需要它工作。我怎样才能在这里做一个深拷贝?请帮忙?