函数在C++中返回"This"对象

dal*_*ngh 3 c++ return this this-pointer

因此,以下是Class 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
Run Code Online (Sandbox Code Playgroud)

当调用该函数时,它被称为

total.combine(trans); //total and trans are the objects of class
Run Code Online (Sandbox Code Playgroud)

我不理解的是函数返回*this,我理解它返回一个对象的实例,但是它没有将这个实例返回给我们在函数调用期间可以看到的任何东西,如果我不写return语句,它会工作吗任何不同.

有人请详细解释,因为我只是没有得到它.

Edg*_*jān 5

这是进行下一次施工的常用方法:

Sales_data x, y, z;
// some code here
auto res = x.combine(y).combine(z);
Run Code Online (Sandbox Code Playgroud)

你打电话的时候:

x.combine(y)
Run Code Online (Sandbox Code Playgroud)

x更改并x返回引用,因此您有机会再次combine()通过在prevous步骤上返回的引用来调用此更改的实例:

x.combine(y).combine(z);
Run Code Online (Sandbox Code Playgroud)

另一个流行的例子是operator=()实施.因此,如果您实现operator=自定义类,则返回对实例的引用通常是个好主意:

class Foo
{
public:
    Foo& operator=(const Foo&)
    {
        // impl
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

这使得作业的分配适用于标准类型:

Foo x, y, z;
// some code here
x = y = z;
Run Code Online (Sandbox Code Playgroud)