gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:37:03 24 4
gpt4 key购买 nike

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

//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/

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