此指针 - 按值返回 vs 按引用返回
this pointer - return by value vs return by reference
关于this
指针,我想听听某人的意见,以下 2 段代码是否实现了相同的功能。
Position Position::operator = (Position pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}
Position & Position::operator = (Position pos)
{
this->x = pos.x;
this->y = pos.y;
}
我知道第一个片段更常用。但是,我想确认第二个代码段是否具有与我使用&
传递对this
对象的引用相同的功能。
在选择所需的选项之前,请注意@RemyLebeau提到的这篇文章: 运算符重载的基本规则和习语是什么?
两者之间的差异示例:
class Position1 {
public:
int x, y;
Position1 operator=(Position1 pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}
};
class Position2 {
public:
int x, y;
Position2& operator=(Position2 pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}
};
int main() {
Position1 p11, p12;
Position2 p21, p22;
//Position1 *p13 = &(p12 = p11); // Compilation error: Taking address of temporary object..
p21.y = 20;
p21.x = 10;
Position2 *p23 = &(p22 = p21); // Working - the `temporary object` is a reference to non temporary object.
p23->x = 99;
p23->y = 84;
cout << p21.x << " " << p21.y; // didn't change
cout << p22.x << " " << p22.y; // changed
cout << p23->x << " " << p23->y; // changed
//===================================================
//(p12 = p11).y = 3; // Compiling error: Expression is not assignable
(p22 = p21).y = 3; // works
cout << p21.x << " " << p21.y << endl; // didn't change
cout << p22.x << " " << p22.y << endl; // changed
return 0;
}
相关文章:
- 返回 str vs. str.substr(0,str.size()) 在 leetcode 中给了我不同的输出
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 返回空字符串文字 VS. 返回空点 - 它们是一样的吗?
- 返回字符串vs通过引用传递字符串以更新值
- 如果语句之后,返回vs无能为力
- 性能:否则如果 vs if 在已经返回的函数中
- C :ScopeGuard vs返回支票和异常处理
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 为什么 VS C++链接器返回具有混合 DLL 转发的"LNK2001: unresolved external symbol"?
- 此指针 - 按值返回 vs 按引用返回
- 返回一个C++引用变量 VS 返回一个变量
- VS C++ 加载库始终返回 null
- 返回对int vs vs返回c 函数中的int的引用
- 崩溃当std ::函数是从lambda返回的VS 2012中返回的值时的崩溃
- C++类函数返回值 VS 对本地数据进行操作
- VS 2010 中返回值的编译器优化
- 按值返回结构体vs按引用返回结构体
- 从函数返回值:引用vs结构
- Java's System.exit(0);vs C++返回 0;
- 在函数外部返回值时使用move vs copy