![]() |
#2
rjsp2021-04-16 08:25
|
在完成+运算之后,函数内部的变量不是会被释放吗?为什么s3的取值正确?

#include <iostream>
#include <string>
using namespace std;
class Stone {
friend Stone& operator + (const Stone& s1, const Stone& s2);
public:
Stone(int weight = 0) { this->weight = weight; }
int getWeight() const { return weight; }
private:
int weight;
};
Stone& operator + (const Stone& s1, const Stone& s2) {
// Stone temp;
// temp.weight = s1.getWeight() + s2.getWeight();
return Stone(s1.getWeight() + s2.getWeight());
}
int main() {
Stone s1(1);
Stone s2(2);
Stone s3;
s3 = s1 + s2;
cout << s3.getWeight() << endl;
cout << s3.getWeight() << endl;
cout << s3.getWeight() << endl;
}
[此贴子已经被作者于2021-4-15 23:13编辑过]