gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:02:13 25 4
gpt4 key购买 nike

所以,下面是类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 的引用,因此您有机会通过上一步再次返回引用:

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;

关于c++ - 在 C++ 中返回 "This"对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44923887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com