返回C++"This"对象的函数
Function returning "This" object in C++
所以,下面是类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
。
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 有没有办法将重载的类函数绑定到函数对象?
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何通过接口将函子分配给函数对象
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 指向std::invoke中成员函数对象的指针
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- "std::function"的简单版本:函数对象的生存期?
- C++ 将函数对象作为左值和/或右值传递
- SFINAE 用于具有默认参数的函数对象
- 构造函数对象赋值是否泄漏内存
- 如何发送通过绑定到函数/方法创建的函数对象?
- std::for_each 与函数对象
- 将函数对象传递给 std::function
- 访问执行策略for_each函数对象中的迭代器
- 通过C++函数对象类访问参数