為什么復制構造函數(shù)的參數(shù)必須為引用呢,原因如下:
Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to need to make a new value, so we call the copy constructor, and so on...
(You would have infinite recursion because "to make a copy, you need to make a copy".)
來源:
http://stackoverflow.com/questions/2685854/why-should-the-copy-constructor-accept-its-parameter-by-reference-in-c
老忘記,舉個例子也許更好理解:
//創(chuàng)建Type類型的對象a
Type a;
//對a的對象內(nèi)部數(shù)據(jù)成員賦值

// 調(diào)用復制構造函數(shù)創(chuàng)建對象b
Type b( a )
由于b的復制構造函數(shù)的參數(shù)被定義為值傳遞,那么首先會創(chuàng)建一個Type的臨時變量,假設為temp1,然后再傳遞給b的復制構造函數(shù)
Type temp1( a )
由于temp1的復制構造函數(shù)的參數(shù)被定義為值傳遞,那么首先會創(chuàng)建一個Type的臨時變量,假設為temp2,然后再傳遞給b的復制構造函數(shù)
Type temp2( a )
類推,會出現(xiàn)temp3,temp4,...直至無窮多!
所以復制構造函數(shù)的參數(shù)必須為引用