我无法弄清楚我正在阅读的书中的以下部分实际上做了什么。
//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" !?
}
我应该说我以前对 C# 有一点了解,并不真正理解 return *this;
究竟如何影响 total object。
最佳答案
琐事
该函数正在返回对与其自身相同的类型的引用,并且它返回...自身。
指针类型
因为返回类型是引用类型(Sales_data&
),而this
是一个指针类型( Sales_data*
),你必须取消引用它,因此 *this
,它实际上是对我们调用其成员函数的对象的引用。
用法
它真正允许的是方法链。
Sales_data total;
Sales_data a, b, c, d;
total.combine(a).combine(b).combine(c).combine(d);
有时是竖写的:
total
.combine(a)
.combine(b)
.combine(c)
.combine(d);
我敢肯定你已经看到了:
cout << "Hello" << ' ' << "World!" << endl;
在上面的例子中,重载了operator<<
返回对输出流的引用。
关于c++ - 不明白return *this "as a whole"的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17891365/