warning: reference to local variable ‘temp’ returned [-Wreturn-local-addr]

当我在用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的内存空间也随机消失了,而我们不能返回一个不存在的地址。

所以不能返回一个地址,把&删掉即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值