这是从一个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;
}
Run Code Online (Sandbox Code Playgroud)
在运算符重载函数中,它创建一个局部变量temp然后返回它,我很困惑,这是正确的方法吗?
"这是正确的方法吗?"
是的.请注意,它不是局部变量,而是实际返回的局部变量的副本,这是完全有效且正确的事情.在通过指针或引用返回时返回局部变量时要小心,而不是在按值返回时返回.