簡體   English   中英

C++ - 返回對調用對象的引用

[英]C++ - Return reference on the calling object

我正在閱讀 Stanley B. Lippman 的 Chapter 7.Classes of C++ Primer 但我對這些代碼有疑問

struct Sales_data{
     string isbn() const { return bookNo;}
     Sales_data& combine(const Sales_data&);
     double avg_price() const;
     string bookNo;
     unsigned units_sold = 0;
     double revenue = 0.0;
};
Sales_data& Sales_data::combine(const Sales_data& rhs){
     units_sold += rhs.units_sold;
     revenue += rhs.revenue;
     return *this;
}

讓我想知道的是,當我們想要更改對象的成員時,返回對 Sales_data 調用對象的引用的方法。

我認為我可以聲明一個 void 方法而不是使用這個方法,我理解的是當一個對象調用combine方法時, units_soldthis->units_sold並且收入this->revenue

出於這個原因,我認為當我想更改對象的成員時,我不必使用返回對調用對象的引用的方法。

void Sales_data::combine(const Sales_data& rhs){
     units_sold += rhs.units_sold;
     revenue += rhs.revenue;
}
// Also change the function in the struct

我已經測試過了,void 方法仍然可以更改調用 combine 方法的對象的成員。 那么這兩種方法有什么區別嗎?

感謝您閱讀並幫助我!

在您的示例中,沒有區別。 要考慮的用例是當有人想要使用combine的結果做其他事情時。 例如:

Sales_data a;
Sales_data b;
// do stuff
Sales_data c = a.combine(b);

這可能通常與賦值運算符一起出現,以便您可以進行鏈式賦值。

Sales_data a, b, c;
// do suff
a = b = c;

在使用構建器類型時,這也是一種有用的模式。

Builder b;
b.set_width(10)
 .set_height(100)
 .set_color(blue);

看到這個,

#include<iostream>

using std::cout;
using std::endl;

class my
{
public:
    int i;
    my& combine(const my& ob);
};

my& my::combine(const my& ob)
{
    this->i+=ob.i;
    return *this;
}

int main()
{
    my ob1,ob2,ob3;

    ob1.i=2;
    ob2.i=2;
    ob3.i=2;

    ob1.combine(ob2).combine(ob3); //you can call member of the class of the returned reference 

    cout<<ob1.i<<endl;             //6

    my ob4=ob1.combine(ob2);       // calls copy constructor if present 
    cout<<ob4.i<<endl;             //8

    my ob5;
    ob5 = ob1.combine(ob2);        // call overloaded = operator if present 
    cout<<ob5.i<<endl;             //10
}

返回引用或無效是您的口味,但是如果您返回引用在上述某些情況下很有幫助但如果您返回無效,則沒有錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM