#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