0

使用這兩個以前的線程爲例重載賦值運算符:如果我們返回(* this),它是指針/地址處的值,賦值運算符的正確語法是什麼?

第一線: Why does overloaded assignment operator return reference to class?

第二個線程: Why must the copy assignment operator return a reference/const reference?

是一個重載賦值運算符類或一類的引用的返回類型?我見過兩個:

Point& Point::operator = (const Point& sourcePoint) 
{ 
// As in the first thread I pasted above 
return *this; 
} 

而且

Point Point::operator = (const Point& sourcePoint) 
{ 
// As in the second thread I pasted above 
return *this; 
} 

哪個是正確的?

同樣,有什麼區別:對戰

int exFunction() 
{ 
    int i = 5; 
    int* iPtr = &i; 
    return *iPtr; 
} 

int& exFunction2() 
{ 
    int j = 5; 
    int* jPtr = &j; 
    return *jPtr; 
} 

謝謝!

回答

1

這兩個行星根本不是「相似的」。

首先,賦值運算符。他們應該返回到對象本身的引用,這樣就可以在鏈中使用它們:

Foo x, y, z; 

x = y = z; // makes y equal to z and returns a reference to self, 
      // which is assigned to x 

所以它總是:

Foo & operator=(Foo const &) { /* ... */ return this; } // copy-assignment 

Foo & operator=(/* any other signature */) { /* ... */ return this; } 

現在,第二個問題:你exFunction2是完全錯誤的,破碎。它有未定義的行爲,因爲它返回一個局部變量的引用,該函數在函數返回時超出了範圍。 (它基本上說是return j;;請記住,取消引用的結果是左值。)編寫該函數的唯一明智的方法是exFunction,它可以縮寫爲int exFunction() { return 5; }

這是關於此主題的a related question

+0

非常感謝,非常感謝! – JZL