2013-07-05 44 views
0

在閱讀「Sams在21天內教你自己C++」時,我無法理解虛擬拷貝構造函數是如何工作的。從書 完整代碼是在這裏: [http://cboard.cprogramming.com/cplusplus-programming/9392-virtual-copy-constructor-help.html][1]Dog拷貝構造函數中聲明瞭什麼[:Mammal(rhs)]?

特別是虛擬方法Clone()調用哺乳動物拷貝構造函數和狗的拷貝構造函數 因爲它返回的「哺乳動物*」,並返回「新狗(*本)」

Mammal::Mammal(const Mammal &rhs):itsAge(rhs.GetAge()) 
    { 
    cout << "Mammal copy constructor\n"; 
    }; 

Dog::Dog (const Dog &rhs):Mammal(rhs) //what is ":Mammal(rhs)" here -  
             // call of Mammal copy constructor? 
             //if not why is it required? 
             //or what is it here? 
{ 
    cout << "Dog copy constructor\n"; 
}; 

又是什麼返回「返回新狗(*本)」? 新對象或新對象的指針?

謝謝你的回答。 P.S. 對不起,我以前的答案與錯誤的標籤。 這是我使用「計算器」的初體驗

+5

請考慮學習[一個很好的C++教科書](http://stackoverflow.com/q/388242/596781)。 –

+0

'new Dog(* this)'將創建一個動態分配的'* this'的副本並將指針返回給該副本。 –

+0

如果你真的想學習C++,請立即停止閱讀,並立即扔掉這本書,並獲得一個體面的一個:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

回答

0
Dog(*this); 

通過調用拷貝構造函數創建類型狗的對象。由於狗從哺乳動物派生,哺乳動物構造函數被調用。特別是,你可以從這個看代碼

Dog::Dog(const Dog & rhs): 
Mammal(rhs) 

是哺乳動物的拷貝構造函數被調用,這是通過RHS作爲參數。

new Dog(*this); 

返回指針啊Dog類型的eap-allocated對象,它使用複製構造函數進行初始化(請參見上文)。當

virtual Mammal* Clone() { return new Dog(*this); } 

被調用時,新運算符返回的Dog *被轉換爲Mammal *並返回。

相關問題