我不明白使用return*这个"整体"

ato*_*red 3 c++

我无法弄清楚我正在阅读的书的下半部分究竟是什么.

//this function supposed to mimic the += operator
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold += rhs.units_sold; // add the members of rhs into
    revenue += rhs.revenue;  // the members of ''this'' object
    return *this; // return the object on which the function was called
}

int main()
{
    //...sth sth

    Sales_data total, trans; 
    //assuming both total and trans were also defined...
    total.combine(trans);
    //and here the book says:
    //we do need to use this to access the object as a whole.
    //Here the return statement dereferences this to obtain the object on which the
    //function is executing. That is, for the call above, we return a reference to total.
    //*** what does it mean "we return a reference to total" !?
}
Run Code Online (Sandbox Code Playgroud)

我应该说我之前对C#有一点了解,并且不太了解究竟是如何return *this;影响总对象的.

Bar*_*icz 14

琐事

该函数返回对与其自身相同的类型的引用,并返回...本身.

指针类型

因为返回的类型是引用类型(Sales_data&),并且this是指针类型(Sales_data*),所以必须取消引用它,因此*this实际上是对我们调用成员函数的对象的引用.

用法

它真正允许的是方法链.

Sales_data total;
Sales_data a, b, c, d;

total.combine(a).combine(b).combine(c).combine(d);
Run Code Online (Sandbox Code Playgroud)

它有时是垂直写的:

total
    .combine(a)
    .combine(b)
    .combine(c)
    .combine(d);
Run Code Online (Sandbox Code Playgroud)

而且我很确定你已经看过了:

cout << "Hello" << ' ' << "World!" << endl;
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,重载operator<<返回对输出流的引用.