返回C++"This"对象的函数

Function returning "This" object in C++

本文关键字:函数 对象 This C++ 返回      更新时间:2023-10-16

所以,下面是类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 语句,它的工作方式会有所不同吗?

有人请详细解释,因为我只是不明白。

这是使下一个构造工作的常用方法:

Sales_data x, y, z;
// some code here
auto res = x.combine(y).combine(z);

当您致电时:

x.combine(y)

x已更改并返回对x的引用,因此您有机会再次通过上一步返回的引用调用此更改的实例combine()

x.combine(y).combine(z);

另一个流行的例子是operator=()实现。因此,如果为自定义类实现operator=,通常最好返回对实例的引用:

class Foo
{
public:
Foo& operator=(const Foo&)
{
// impl
return *this;
}
};

这使得作业适用于您的类,因为它适用于标准类型:

Foo x, y, z;
// some code here
x = y = z;

定义return语句定义的函数的一个好处是,它允许像下面的代码一样连续调用:

// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1).combine(trans2);
// now total contains values from trans1 and trans2

这相当于:

// assuming that trans1 and trans2 are defined and initialized properly earlier
total.combine(trans1);
total.combine(trans2);
// now total contains values from trans1 and trans2

但它更简洁和简短。

但是,如果您不需要或喜欢使用早期版本,则可以声明函数以返回void

我知道

它返回对象的一个实例,但它不会像我们在函数调用期间看到的那样将该实例返回给任何内容

正确,在这种情况下。

但是,如果需要,可以使用返回值。它在那里以防万一。

这是一个常见的约定,允许函数调用链接

另外,如果我不写 return 语句,它的工作方式会有所不同吗?

它将具有未定义的行为,因为该函数具有返回类型,因此必须返回某些内容。但是,当然,您可以在不更改此特定程序功能的情况下使返回类型void