这是网站上的示例:http://www.cplusplus.com/doc/tutorial/classes2/ 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;
}
在您的示例中,您不返回对象引用,而只是按值返回对象。
事实上,对象 temp 在函数退出后被销毁,但此时它的值已复制到堆栈上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)