c++ - 返回对调用对象的引用 (C++)
问题描述
有点难以理解这段代码:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
为什么我们必须返回“*this”作为参考而不是仅仅返回“*this”?
解决方案
如果setX
改为
Test setX(int a) { x = a; return *this; }
然后它返回一个副本而*this
不是对它的引用。所以在
obj1.setX(10).setY(20);
thesetY
在副本上调用,而不是在obj1
其自身上调用。副本被丢弃,并且obj1.y
永远不会从其初始值 5 修改。
推荐阅读
- ios - 如何在仅在一个国家/地区提供的 iOS 应用中处理其他国家/地区的应用内购买?
- python - 获取图像的定义线(更平滑的精明边缘检测?)
- java - 编译器无法推断泛型类型、参数不匹配(Java)
- node.js - 在我的反应项目 os.networkInterfaces() 返回空对象,但控制台返回正确的结果
- flutter - 在小部件树中检测到重复的 GlobalKey。在表单验证中
- visual-studio-code - 工作区和 wls 的配置设置
- pytest - pytest.mark.parametrize 使用来自全局夹具的值
- sql - 按级别更新连接请检查我在哪里做错了
- java - 自动对焦开启,但使用 Android Camera2 API 锁定缩放,为什么图像被缩放?
- sas - 计算每个问题的正确百分比