这是来自网站的示例:http://www.cplusplus.com/doc/tutorial/classes2/
我知道这是一个可行的例子。但是,我不明白为什么可以从operator +重载函数返回对象temp。除了代码外,我还发表了一些评论。
// 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); ***// Isn't object temp be destroyed after this function exits ?***
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b; ***// If object temp is destroyed, why does this assignment still work?***
cout << c.x << "," << c.y;
return 0;
}
最佳答案
在您的示例中,您不返回对象引用,而只是按值返回对象。
实际上,在函数退出后,对象临时对象将被销毁,但到那时该对象的值将被复制到堆栈中。