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

时间:2012-10-25 20:57:35

标签: c++ operator-overloading pass-by-reference assignment-operator

使用前两个线程作为示例

第一个帖子: Why does overloaded assignment operator return reference to class?

第二个帖子: Why must the copy assignment operator return a reference/const reference?

重载赋值运算符的返回类型是类还是类的引用?我见过两个:

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;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

这两个方面根本不是“相似”。

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

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; }。< / p>

此主题为a related question

相关问题