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