m0_63743798 2022-03-22 17:31 采纳率: 50%
浏览 32
已结题

c++递减运算符重载出现的问题

图上的未经处理的异常是怎么回事?之前有人说是<<那的第二个&要去掉,可是明显不行,那样cout会因为局部不能进行两次--.帮忙解答一下这里的问题到底是什么呢谢谢!

img

img

  • 写回答

2条回答 默认 最新

  • 关注

    后置++改成下面的:

    my operator --(int)
        {
            my temp ;
            temp.m_num = this->m_num;
            this->m_num--; //这里本类的要--
            return temp; //返回的是原来的值
        }
    
    

    运行结果:

    img

    完整代码:

    #include <iostream>
    using namespace std;
    
    class my 
    {
        friend ostream& operator<<(ostream& cout, my myint);
    public:
        my() {
            m_num = 0;
        }
        my& operator --()
        {
            m_num--;
            return *this;
        }
        my operator --(int)
        {
            my temp ;
            temp.m_num = this->m_num;
            this->m_num--; //这里本类的要--
            return temp; //返回的是原来的值
        }
    private:
        int m_num;
    };
    
    ostream& operator<<(ostream& cout, my myint)
    {
        cout << myint.m_num;
        return cout;
    }
    
    void test01()
    {
        my myint;
        cout << --(--myint) << endl;
        cout << myint << endl;
    }
    
    void test02()
    {
        my youint;
        cout << youint-- << endl;
        cout << youint << endl;
    }
    
    int main()
    {
        //test01();
        test02();
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月30日
  • 已采纳回答 3月22日
  • 创建了问题 3月22日

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗