关于函数返回到底是值还是引用
注意重载的+运算符,这里我返回的是引用(按道理这里应该是不能返回引用的),但是为什么s3的结果却能正确打印?在完成+运算之后,函数内部的变量不是会被释放吗?为什么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编辑过]








