哈夫曼树_ 2023-01-27 16:54 采纳率: 57.7%
浏览 15
已结题

后置自增运算符重载的返回值类型

img

红框处,返回的temp是局部变量,当函数MyInteger& operator++(int)执行完成后,temp应该会被销毁,无法用引用类型返回。为什么这里却可以运行?(编译器是VS2022)


#include<iostream>
using namespace std;

class MyInteger
{
    friend ostream& operator<<(ostream& cout, MyInteger myInt);
    int m_num;

public:
    MyInteger()
    {
        m_num = 0;
    }

    MyInteger(int num)
    {
        m_num = num;
    }

    // 前置自增运算符重载
    MyInteger& operator++()
    {
        ++m_num;
        return *this;
    }

    // 前置自减运算符重载
    MyInteger& operator--();

    // 后置自增运算符重载
    MyInteger& operator++(int)   // 此处的int为占位参数, 构成函数重载
    {
        MyInteger temp = *this;
        m_num++;
        return temp;
    }

    // 后置自减运算符重载
};

// 前置自减运算符重载
MyInteger& MyInteger::operator--()
{
    --m_num;
    return *this;
}

ostream& operator<<(ostream& cout, MyInteger myInt)
{
    cout << myInt.m_num;
    return cout;
}

void test01()
{
    MyInteger myInt;
    cout << ++myInt << endl;
    cout << --myInt << endl;
}

void test02()
{
    MyInteger myInt;
    cout << myInt++ << endl;
    cout << myInt++ << endl;
    //cout << myInt-- << endl;
}

int main()
{
    // test01();
    test02();

    system("pause");
    return 0;
}
  • 写回答

2条回答 默认 最新

  • Lanlan089 2023-01-27 17:13
    关注

    在C++语言中,可以将一个自动变量转换为引用类型,即将一个局部变量的引用返回。这也就是为什么在函数myinteger& operator++(int)中,可以将temp作为引用类型返回的原因。此处应当注意的是,在该函数返回时,temp变量仍然存在,能够正常使用,但当函数结束时,temp变量会立刻被销毁,此时再使用temp变量可能会发生未定义的错误。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月7日
  • 已采纳回答 1月30日
  • 创建了问题 1月27日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)