什么'返回*这个'实际上呢?

时间:2018-02-18 17:26:05

标签: c++ c++11

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; 
}

返回此做什么?

3 个答案:

答案 0 :(得分:12)

return *this返回当前对象(作为参考),这意味着如果您在之前的呼叫中呼叫Sales_data,现在可以在combine上链接函数调用。这意味着这样的事情可行:

Sales_data t;
t.combine(a).combine(b).combine(c); // Assuming a, b, and c are other Sales_data's

这是一种非常有用的技术,允许您创建fluent interface,进一步允许您使用诸如named parameter idiom之类的内容,并且存在于各种编程语言中。

答案 1 :(得分:1)

它返回指向当前Sales_data对象(此成员函数调用的对象)的指针,其中包含units_sold和revenue的更新值。

我想通过这个功能,你试图通过组合另一个来更新当前销售数据中的值。

是的,正如@Arnav所说,它可以用于链接,因为它总是返回你的对象地址。

答案 2 :(得分:0)

它返回对象 - 在这种情况下是对使用的对象的引用