3

这是从其中一个 c++ 教程中摘录的:

// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

在运算符重载函数中,它创建一个本地 vartemp然后返回它,我很困惑,这是正确的方法吗?

4

2 回答 2

5

“这是正确的方法吗?”

是的。请注意,它不是局部变量,而是实际返回的局部变量的副本,这是完全有效且正确的做法。在通过指针或引用返回时要小心返回局部变量,而不是在按值返回时

于 2013-11-09T22:05:44.990 回答
1

是的,因为它是按值返回的。如果该函数具有以下签名,则它是不正确的:

CVector& CVector::operator+(CVector param);

顺便说一句,更有效的实现如下所示:

CVector CVector::operator+(const CVector &param) const;
于 2013-11-09T22:06:33.553 回答