[英]Function returning “This” object in C++
因此,以下是類Sales_data的成員函數,它在類外定義,
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語句,它的工作方式不同。
有人請詳細解釋,因為我只是沒有得到它。
這是進行下一次施工的常用方法:
Sales_data x, y, z;
// some code here
auto res = x.combine(y).combine(z);
你打電話時:
x.combine(y)
x
被更改並返回對x
引用,因此您有機會通過再次在prevous步驟上返回的引用再次調用此更改實例上的combine()
:
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;
使用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
。
我理解它返回一個對象的實例,但它沒有將該實例返回給我們在函數調用期間可以看到的任何內容
在這種情況下,正確。
但是如果你願意,你可以使用返回值。 它就是為了以防萬一。
這是一種常見的約定,允許函數調用鏈接 。
另外,如果我不寫return語句,它會以不同的方式工作。
它將具有未定義的行為,因為該函數具有返回類型,因此必須返回一些東西 。 但是你肯定可以在不改變這個特定程序的功能的情況下使返回類型為void
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.