c++ - 不明白return *this "as a whole"的用法

标签 c++

我无法弄清楚我正在阅读的书中的以下部分实际上做了什么。

//this function supposed to mimic the += operator
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold += rhs.units_sold; // add the members of rhs into
    revenue += rhs.revenue;  // the members of ''this'' object
    return *this; // return the object on which the function was called
}

int main()
{
    //...sth sth

    Sales_data total, trans; 
    //assuming both total and trans were also defined...
    total.combine(trans);
    //and here the book says:
    //we do need to use this to access the object as a whole.
    //Here the return statement dereferences this to obtain the object on which the
    //function is executing. That is, for the call above, we return a reference to total.
    //*** what does it mean "we return a reference to total" !?
}

我应该说我以前对 C# 有一点了解,并不真正理解 return *this; 究竟如何影响 total object。

最佳答案

琐事

该函数正在返回对与其自身相同的类型的引用,并且它返回...自身。

指针类型

因为返回类型是引用类型(Sales_data&),而this是一个指针类型( Sales_data* ),你必须取消引用它,因此 *this ,它实际上是对我们调用其成员函数的对象的引用

用法

它真正允许的是方法链。

Sales_data total;
Sales_data a, b, c, d;

total.combine(a).combine(b).combine(c).combine(d);

有时是竖写的:

total
    .combine(a)
    .combine(b)
    .combine(c)
    .combine(d);

我敢肯定你已经看到了:

cout << "Hello" << ' ' << "World!" << endl;

在上面的例子中,重载了operator<<返回对输出流的引用。

关于c++ - 不明白return *this "as a whole"的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17891365/

相关文章:

c++ - 非常基本的正则表达式场景与我对 libstdc++-v3 的预期不同

c++ - 是否有一个 lint 工具可以检查子类虚函数是否与父类定义匹配?

c++ - 核心转储,找不到原因

c++ - 如何从 C 文件调用 C++ 构造函数

c++ - 在 Windows 上分发( native C++)库

android - 在 OpenCV 上。 C++ 编译器无法编译简单的测试程序。使用 Clang++

c++ - Qt 的 CUDA 包装器

C++赋值运算符解析

c++ - 正则表达式替换为 c++11 中的回调?

c++ - 消除低效代码