【发布时间】:2010-09-30 14:10:57
【问题描述】:
#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 说
“由于克隆方法是一种 对象的实际类,它可以 还创建一个深拷贝。它可以访问 它所属的类的所有成员 到,所以那里没有问题。”
我不明白深拷贝是如何发生的。在上面的程序中,甚至没有发生浅拷贝。 即使 Base 类是抽象类,我也需要它工作。我怎样才能在这里做一个深拷贝?请帮忙?
【问题讨论】:
-
Clone() 不是你在 C++ 中看到的(经常)。您要移植 Java 应用程序吗?
-
没有。我正在尝试在 C++ 中进行深度复制,一些 C++ 程序员创建了他们自己的 clone() 函数,如上所示。当您点击“我的问题与这个、这个和这个帖子有关”中显示的链接时,会更清楚。 (引号中的句子显示在我上面的问题中)
标签: c++ virtual deep-copy shallow-copy