【发布时间】:2017-07-05 10:37:18
【问题描述】:
所以,下面是类 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 语句,它的工作方式是否会有所不同。
有人请详细解释,因为我只是不明白。
【问题讨论】:
-
提示:使用调试器单步执行
total.combine(trans1).combine(trans2).combine(trans3); -
这个对象的副本将被写入堆栈,但不会被读取,并且会在下一刻被丢弃
-
@Arkady - 不会有副本。注意返回类型。
-
Tihs 已完成以启用链接。 en.wikipedia.org/wiki/Method_chaining
-
哦,你是对的)
标签: c++ return this this-pointer