2012-10-29 31 views
0

我是新來複制構造函數的概念。我有一個基本問題。 希望實施類似深層應對C++ - 如果給出指向該類的類的副本,請給出類

orig *f1(orig*o) 
{ 
    // Returns a copy of *0 and should deep copy all the values of the parent 
    // pointer.Planning to implement a copy constructor to achieve the same. 
    // Can anyone provide a prototype or some idea on the same? 
} 
class dummyclass 
{ 
int value; 
}; 
class orig 
{ 
    dummyclass *dummy; 
    char str[100]; 
public: 
//default constructor 
: 
//parametrised constructor 
orig(char *p) 
{ 
    dummy = new dummyclass; 
    //rest of the initialisation 
} 
orig(const orig& duplicate) 
{ 
//copy constructor 
} 
}; 
int main() 
{ 
    orig o("Hello");//constructor 
    orig dup(o);//copy constructor 
    } 

我知道這樣,我們可以調用拷貝constructor.But如果指針鄰即*Ø給出如何調用拷貝構造函數,做深拷貝功能。

+0

當希望你可以調用拷貝構造函數按照馬克·加西亞的回答。你可以從指針創建一個構造函數 - 它應該做複製構造函數應該做的事情 - 'dummy = new dummyclass(p-> dummy); std :: copy(str,p-> str,p-> str + 100);'。你需要一個析構函數來「刪除虛擬」。在'dummyclass'上有一個'clone()'函數是一個更加結構化的方法,但是對於一個'int'成員來說是過度的。 –

+0

@TonyD實際上,使用指針已經在* overkill *這裏了。 –

回答

2

然後取消引用o

orig* o = new orig("Hello"); 
orig dup(*o); 
+0

所以基本上我可以做這個orig * f1(orig * o){orig dup(* o);返回* dup; }另外,如果我們有一個複製構造函數是否需要重載賦值運算符? – user1495948

+0

你可以做到這一點,但你*應該*的返回值是一個動態分配的變量(否則它只是返回一個指向一個不存在的對象的指針)。 –

+0

你的意思是在複製構造函數中,我應該做dup = new orig並複製每個值? – user1495948