gpt4 book ai didi

C++ 编译器警告 - 返回局部变量

转载 作者:IT老高 更新时间:2023-10-28 22:35:12 25 4
gpt4 key购买 nike

我只是想重载一个 + 运算符,我收到了这个编译器警告

reference to local variable 'tmp' returned

这里是重载的代码

const Int& Int::operator+(const Int& p) const
{
Int tmp = value + p.value;
return tmp;
}

这是类(class)

class Int{
int value;
public:
Int() {} // default constructor
Int(int v) : value(v) {}
Int& operator=(const Int&);
const Int& operator+(const Int&) const;
};

最佳答案

您不能返回对局部变量的引用。在 operator+() 函数中,您正在创建一个名为 tmp 的局部变量。一旦函数退出,它将被销毁。您不能返回对该变量的引用,因为当调用函数获得返回值时它不再存在。

将函数的定义更改为:

const Int operator+(const Int&) const;

它会在没有警告的情况下构建并且也可以正常工作。

关于C++ 编译器警告 - 返回局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1303947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com