2013-05-31 23 views
3

我有一個程序,它被示出拷貝construtor稱爲額外

#include <cstdlib> 
#include <iostream> 

using namespace std; 
class man{ 
      int i ; 
     public: 
      man(){ 
      i=23; 
      cout << "\n defaul constructir called\t"<< i<<"\n"; 
      } 
      man (const man & X) { 
       i = 24; 
      cout << "\n COPY constructir called\t"<< i<<"\n"; 
      }  
      man & operator = (man x) { 
       i = 25; 
       cout << "\n = operator called\t"<< i<<"\n"; 
       return *this; 
      }  
     }; 

int main(int argc, char *argv[]) 
{ 

    man x; 
    cout <<"\n ----------\n"; 
    man y = x; 
    cout <<"\n ----------\n"; 
    x=y; 


    return 0; 
} 

defaul constructir called 23 

---------- 

COPY constructir called 24 

---------- 

COPY constructir called 24 

= operator called 25 

該輸出是奇怪對於x = y的第三呼叫所示的輸出怪異的行爲;

爲什麼當我沒有製作一個新對象但正在使用舊對象時,調用了複製構件的額外打印。

它是介於兩者之間監守臨時對象,如果是我可以在這裏阻止他們....

回答

3
man& operator =(man x); 

你參數接受其參數逐,,這時它會調用拷貝構造函數。這是什麼導致額外的不受歡迎的電話。按引用傳遞你的論點會避免一個副本,但隨後你將無法通過臨時對象(通常被稱爲右值):

struct man 
{ 
    man& operator =(man& x) { return *this; }; 
}; 

int main() 
{ 
    man a, b; 

    a = b;  // works 
    a = man(); // error: no viable overloaded '=', 
       // expected an l-value for 1st argument 
} 

引用傳遞到const將使雙方的副本建設左值和右值:

man& operator =(man const& x); 
//     ^^^^^ 
12

因爲你的賦值運算符按值接受其參數。你可以通過const引用來代替它。

+0

謝謝@OilCharlesworth。 – MAG