注册 登录
编程论坛 C++教室

关于函数返回到底是值还是引用

大爱CATs 发布于 2021-04-15 23:11, 1366 次点击
注意重载的+运算符,这里我返回的是引用(按道理这里应该是不能返回引用的),但是为什么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编辑过]

3 回复
#2
rjsp2021-04-16 08:25
但是为什么s3的结果却能正确打印?
因为你这属于“未定义行为”。
“未定义行为”什么都不保证,既不保证一定正确,当然也不保证一定错误。
#3
大爱CATs2021-04-16 10:11
回复 2楼 rjsp
多谢您 我明白了
#4
Potheads2021-04-16 14:22
1