為什么復制構造函數的參數必須為引用呢,原因如下:
來源:
老忘記,舉個例子也許更好理解:
由于b的復制構造函數的參數被定義為值傳遞,那么首先會創建一個Type的臨時變量,假設為temp1,然后再傳遞給b的復制構造函數
由于temp1的復制構造函數的參數被定義為值傳遞,那么首先會創建一個Type的臨時變量,假設為temp2,然后再傳遞給b的復制構造函數
類推,會出現temp3,temp4,...直至無窮多!
所以復制構造函數的參數必須為引用
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
老忘記,舉個例子也許更好理解:
//創建Type類型的對象a
Type a;
//對a的對象內部數據成員賦值

// 調用復制構造函數創建對象b
Type b( a )
Type a;
//對a的對象內部數據成員賦值

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