2010-09-30 44 views
0
#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 

我的问题是有关thisthisthis后。

在第一个环节,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."

我不明白深副本是如何发生的。在上面的程序中,甚至没有发生浅拷贝。 即使基类是抽象类,我也需要它。我怎样才能在这里做一个深层复制?请帮助?

+0

Clone()不是你在C++中经常看到的东西。你正在移植一个Java应用程序吗? – 2010-09-30 14:28:45

+0

不,我想在C++中进行深层复制,并且一些C++程序员创建了他们自己的clone()函数,如上所示。当您按照“我的问题与此相关,本文和本文”中显示的链接时,这将更加清楚。 (引号中的句子显示在上面的问题中) – Nav 2010-09-30 14:39:05

回答

5

那么,你的拷贝构造函数什么都不做,所以你的clone方法在拷贝的时候什么也不做。

见行Derived(const Derived&) {}

编辑:如果您添加的代码通过转让复制所得的全部成员,它会成为一个浅拷贝。如果您还复制(通过创建一个新实例)您的实例,它将成为一个深层复制。

+1

+1!该代码不会复制任何内容。深拷贝要求在拷贝构造函数中手动完成拷贝。 – jwueller 2010-09-30 14:18:44

+0

我明白了。所以拥有克隆方法的唯一目的是返回一个Base类型的指针。无论如何都需要手动复制结构。叹!感谢您的回复:) – Nav 2010-09-30 14:27:11

+0

小增加:默认拷贝构造函数创建一个浅拷贝。如果你需要一些东西的浅拷贝,你不需要手动去做。 – jwueller 2010-09-30 14:29:23