当我在用C++编程时,遇到了warning: reference to local variable ‘temp’ returned [-Wreturn-local-addr]
的错误。
这是我出错的源代码。
#include <iostream>
using namespace std;
class Date
{
int d;
public:
Date(int dd) : d(dd) {}
void Print() { cout << d << endl; }
Date &operator++(int a)
{
Date temp = *this;
this->d++;
return temp; //就是这里。
}
};
int main()
{
Date d(14);
d++;
d.Print();
}
解决方案:将Date &operator++(int a)
改为Date operator++(int a)
就行,把&
删掉即可。
原因:在原来的代码里面,表示引用的符号&
暗示函数返回的是一个地址,但要注意temp
是一个临时变量,当函数体执行结束时,temp
的内存空间也随机消失了,而我们不能返回一个不存在的地址。
所以不能返回一个地址,把&
删掉即可。