【问题标题】:Function returning "This" object in C++在 C++ 中返回“This”对象的函数
【发布时间】: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


【解决方案1】:

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

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;

【讨论】:

    【解决方案2】:

    使用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

    【讨论】:

      【解决方案3】:

      我知道它返回对象的一个​​实例,但它没有将该实例返回给我们在函数调用期间可以看到的任何东西

      正确,在这种情况下。

      但如果您愿意,可以使用返回值。以防万一。

      这是一个通用约定,允许函数调用链接

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

      它将具有未定义的行为,因为该函数具有返回类型,因此必须返回 something。但是你可以在不改变这个特定程序的功能的情况下设置返回类型void,当然。

      【讨论】:

        猜你喜欢
        • 2012-09-11
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 2014-04-08
        • 2021-08-09
        • 1970-01-01
        • 2019-05-19
        • 1970-01-01
        相关资源
        最近更新 更多