2017-07-05 112 views
3

因此,以下是在上述類外定義類SALES_DATA的成員函數,函數返回「這」對象在C++

Sales_data& Sales_data::combine(const Sales_data &rhs) { 
    units_sold += rhs.units_sold; 
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object 
    return *this; 
} //units_sold and revenue are both data members of class 

當函數被調用時,它被稱爲像

total.combine(trans); //total and trans are the objects of class 

什麼我不理解是返回*this, 我理解它返回的對象實例的功能,但它不返回該實例的任何東西,因爲我們可以函數調用過程中看到,另外,如果我不寫return語句, 將它的工作方式不同。

有人請解釋精心因爲我只是沒有得到它。

+4

提示:使用調試器遍歷'total.combine(trans1).combine(trans2).combine(trans3);' – StoryTeller

+0

該對象的副本將被寫入堆棧,但不會被讀取,並且將被讀取丟棄的下一個時刻 – Arkady

+3

@Arkady - 將不會有副本。請注意返回類型。 – StoryTeller

回答

5

它是使未來建設工作的常用方法:

Sales_data x, y, z; 
// some code here 
auto res = x.combine(y).combine(z); 

當你撥打:

x.combine(y) 

x改變並返回參考x,讓你有機會調用combine()在這個變化的情況下通過對prevous一步參考返回一次時間:

x.combine(y).combine(z); 

另一個流行的例子是operator=()的實現。所以,如果你實現operator=自定義類往往是一個好主意,返回實例的引用:

class Foo 
{ 
public: 
    Foo& operator=(const Foo&) 
    { 
     // impl 
     return *this; 
    } 
}; 

這使得你的類分配的工作,因爲它適用於標準類型:

Foo x, y, z; 
// some code here 
x = y = z; 
1

我理解它返回的對象的實例,但不返回該實例的任何東西,因爲我們可以在函數調用期間看到

正確的,在這種情況下。

但是你可以如果你想使用的返回值。它在那裏以防萬一。

這是一個常見的約定,允許函數調用

此外,如果我不寫return語句,它會以任何不同的方式工作。

它會有未定義的行爲,因爲該函數有返回類型,因此必須返回。但是,您可以在不改變此特定程序的功能的情況下製作返回類型void

2

定義爲您與return語句定義的函數的一個好處是它允許連續調用像下面可能的代碼:

// assuming that trans1 and trans2 are defined and initialized properly earlier 
total.combine(trans1).combine(trans2); 
// now total contains values from trans1 and trans2 

這相當於:

// assuming that trans1 and trans2 are defined and initialized properly earlier 
total.combine(trans1); 
total.combine(trans2); 
// now total contains values from trans1 and trans2 

但稍微簡潔一點。

但是,如果您不需要或不想使用早期版本,則可以聲明函數返回void