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

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

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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程