繁体   English   中英

重载赋值运算符:如果我们返回(* this),它是指针/地址处的值,那么赋值运算符的正确语法是什么?

[英]Overloading assignment operator: if we return (*this), which is a value at a pointer/address, what's right syntax for assignment operator?

以前面的两个线程为例

第一线程: 为什么重载的赋值运算符返回对类的引用?

第二个线程: 为什么拷贝赋值运算符必须返回引用/常量引用?

重载的赋值运算符的返回类型是类还是对类的引用? 我都看过:

Point& Point::operator = (const Point& sourcePoint)
{
// As in the first thread I pasted above
return *this;
}

Point Point::operator = (const Point& sourcePoint)
{
// As in the second thread I pasted above
return *this;
}

哪个是对的?

同样,两者之间有什么区别?

int exFunction()
{
     int i = 5;
     int* iPtr = &i;
     return *iPtr;
}

与:

int& exFunction2()
{
     int j = 5;
     int* jPtr = &j;
     return *jPtr;
}

谢谢!

这两个种族根本不是“相似”的。

首先,赋值运算符。 它们应该返回对对象本身的引用,以便您可以在链中使用它们:

Foo x, y, z;

x = y = z;   // makes y equal to z and returns a reference to self,
             // which is assigned to x

所以总是这样:

Foo & operator=(Foo const &) { /* ... */  return this; }  // copy-assignment

Foo & operator=(/* any other signature */) { /* ... */   return this; }

现在,第二个问题:您的exFunction2完全错误且已损坏。 它具有未定义的行为,因为它返回对局部变量的引用,该局部变量在函数返回时已超出范围。 (它表示本质上是return j;请记住,解除引用的结果是一个左值。)编写该函数的唯一明智的方法是类似于exFunction ,可以将其简化为int exFunction() { return 5; } int exFunction() { return 5; }

这是此主题相关的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM