#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说
"Since the clone-method is a method of the actual class of the object, it can also create a deep-copy. It can access all members of the class it belongs to, so no problems there."
我不明白深副本是如何发生的。在上面的程序中,甚至没有发生浅拷贝。 即使基类是抽象类,我也需要它。我怎样才能在这里做一个深层复制?请帮助?
Clone()不是你在C++中经常看到的东西。你正在移植一个Java应用程序吗? – 2010-09-30 14:28:45
不,我想在C++中进行深层复制,并且一些C++程序员创建了他们自己的clone()函数,如上所示。当您按照“我的问题与此相关,本文和本文”中显示的链接时,这将更加清楚。 (引号中的句子显示在上面的问题中) – Nav 2010-09-30 14:39:05