蹲家宅宅 2023-10-23 16:29 采纳率: 52%
浏览 2
已结题

请问cpp中为什么不能输出重载后的后置递增运算符的值?

请问cpp中为什么不能输出重载后的后置递增运算符的值?


# include<iostream>

using namespace std;


class myInt
{
    friend ostream& operator<<(ostream& cout,myInt& a);
private:
    int m_num;
public:
    myInt(){
        m_num = 0;
    };
    //前置递增运算符重载
    myInt& operator++(){
        m_num++;
        return *this;
    }
    //后置递增运算符重载
    myInt operator++(int){//int是占位符
        myInt temp = *this;
        m_num++;
        return temp;
    }
};

//<<重载
ostream& operator<<(ostream& cout,myInt& a){
    cout << a.m_num;
    return cout;
}

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



int main(){
    myInt m_int;
    cout << m_int << endl;
    cout << ++m_int << endl;
    cout << m_int << endl;
    cout << m_int++ << endl;

    
}
  • 写回答

2条回答 默认 最新

  • 关注

    右值引用

    #include <iostream>
    
    using namespace std;
    
    class myInt
    {
        friend ostream &operator<<(ostream &cout, myInt &a);
    
        friend ostream &operator<<(ostream &cout, myInt &&a);
    
      private:
        int m_num;
    
      public:
        myInt()
        {
            m_num = 0;
        };
        // 前置递增运算符重载
        myInt &operator++()
        {
            m_num++;
            return *this;
        }
        // 后置递增运算符重载
        myInt operator++(int)
        { // int是占位符
            myInt temp = *this;
            m_num++;
            return temp;
        }
    };
    
    //<<重载
    ostream &operator<<(ostream &cout, myInt &a)
    {
        cout << a.m_num;
        return cout;
    }
    
    ostream &operator<<(ostream &cout, myInt &&a)
    {
        cout << a.m_num;
        return cout;
    }
    
    int main()
    {
        myInt m_int;
        cout << m_int << endl;
        cout << ++m_int << endl;
        cout << m_int << endl;
        cout << m_int++ << endl;
    }
    
    
    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月9日
  • 专家已采纳回答 11月1日
  • 创建了问题 10月23日

悬赏问题

  • ¥20 Html备忘录页面制作
  • ¥15 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?
  • ¥20 数学建模来解决我这个问题
  • ¥15 计算机网络ip分片偏移量计算头部是-20还是-40呀
  • ¥15 stc15f2k60s2单片机关于流水灯,时钟,定时器,矩阵键盘等方面的综合问题
  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?
  • ¥15 django5安装失败