2010-09-30 59 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