风过无痕921 2022-08-13 11:16 采纳率: 86.4%
浏览 52
已结题

有关C++运算符重载的几个问题

问题遇到的现象和发生背景 C++中的运算符重载
问题相关代码,请勿粘贴截图
#include<iostream>
#include<string>
using namespace std;

class MyInt
{
    
    friend ostream& operator<<(ostream &cout,MyInt A);
    friend void test01();
    
    public:
        
        MyInt& operator++()
        {
            this->m_A++;
            this->m_B++;
            return *this;
        }
        
        MyInt operator++(int)
        {
            MyInt temp;
            temp.m_A=this->m_A;
            temp.m_B=this->m_B;
            this->m_A++;
            this->m_B++;
            return temp;
        }
        
    private:
        int m_A;
        int m_B;
};

ostream& operator<<(ostream &cout,MyInt A)
{
    cout<<"m_A = "<<A.m_A<<endl<<"m_B = "<<A.m_B;
    return cout;
}

void test01()
{
    MyInt MI1;
    MI1.m_A=0;
    MI1.m_B=0;
    cout<<"MI1(0,0)的++MI1:"<<endl<<++MI1<<endl;
    MyInt MI2;
    MI2.m_A=0;
    MI2.m_B=0;
    cout<<"MI2(0,0)的MI2++:"<<endl<<MI2++<<endl;
}

int main()
{
    test01();
    system("pause");
    return 0;
}

运行结果及报错内容

上面的代码可以正确运行,但是将ostream& operator<<(ostream &cout,MyInt A)改为ostream& operator<<(ostream &cout,MyInt &A)之后就会报错,cout<<"MI2(0,0)的MI2++:"<<endl<<MI2++<<endl;会标红。

  • 写回答

3条回答 默认 最新

  • 真相重于对错 2022-08-13 16:06
    关注

    ostream& operator<<(ostream &cout,MyInt A)
    改引用的话需要把它改成const MyInt& ,因为A++ ,返回的是临时变量不能用左值引用绑定他

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

报告相同问题?

问题事件

  • 系统已结题 8月27日
  • 已采纳回答 8月19日
  • 创建了问题 8月13日