2
class sample 
{ 
    private: 
    int radius; 
    float x,y; 
    public: 
    circle() 
    { 

    } 
    circle(int rr;float xx;float yy) 
    { 
     radius=rr; 
     x=xx; 
     y=yy; 
    } 

circle operator =(circle& c) 
    { 
     cout << endl<<"Assignment operator invoked"; 
     radius=c.radius; 
     x=c.x; 
     y=c.y; 
     return circle(radius,x,y); 
    } 


} 

int main() 
{ 
circle c1(10,2.5,2.5); 
circle c1,c4; 
c4=c2=c1; 
} 

在重載「=」函數的聲明爲什麼重載操作符需要返回=對象?

radius=c.radius; 
x=c.x; 
y=c.y; 

本身使所有C2的數據成員等於C1的,那麼,爲什麼是必要的回報? 類似地,在c1 = c2 + c3中,使用重載的+運算符添加c2和c3,並將該值返回給c1,但不會變爲c1 =,所以我們不應該使用another =運算符來分配c2和c3之和爲c1?我很困惑。

+0

相關:http://stackoverflow.com/questions/2447696/overloading-assignment-operator-in-c和http://stackoverflow.com/questions/2649068/has-anyone-found-the-need-to -declare最返回參數的,一個拷貝賦值-O/2649576#2649576 – 2012-04-11 16:25:09

回答

6

這不是需要(即一個void返回類型是合法的),但標準的做法是參考返回*this允許分配鏈沒有任何效率的開銷。例如: -

class circle 
{ 
    int radius; 
    float x, y; 

public: 
    circle() 
     : radius(), x(), y() 
    { } 

    circle(int rr, float xx, float yy) 
     : radius(rr), x(xx), y(yy) 
    { } 

    circle& operator =(circle const& c) 
    { 
     std::cout << "Copy-assignment operator invoked\n"; 
     radius = c.radius; 
     x = c.x; 
     y = c.y; 
     return *this; 
    } 
}; 

int main() 
{ 
    circle c1(10, 2.5f, 2.5f); 
    circle c2, c3; 
    c3 = c2 = c1; 
} 

通過返回一個新的對象,因爲你正在做的,肯定是不規範的,因爲它創建不必要的臨時。

2

這是爲了支持a = b = c的習語。

你也做錯了;退貨應該是circle &而不是circle,退貨應該是return *this;

0

您可以從您的賦值運算符函數返回* this來返回對當前對象的引用。您也可以的

circle& operator = (circle& c) 
{ 
// do assignments 
    return *this; 
} 
3

這不是強制性的價值,而是返回一個參考*this讓人們鏈的分配,你可以與基本類型。

但是,只有賦值運算符根據值或const引用採用其參數時纔會起作用;你的電話號碼爲非const,這是你在特殊情況下應該做的事情。

circle & operator=(circle const & c) { 
    radius = c.radius; 
    x = c.x; 
    y = c.y; 
    return *this; 
} 

有了這樣的運營商,c4=c2=c1將編譯,將分配給c1c2,那麼c2新值分配給c4的效果。

相關問題