汉沛道丰 2023-01-06 23:11 采纳率: 50%
浏览 22
已结题

代码中那里有问题,自学的不知怎么解决

在自学C++到递增运算符重载时
在类中用成员函数实现递增重载,前置没有报错,后置报错说没有合适的运算符

#include <iostream>
#include <string>
using namespace std;
class MyInteger {
    friend ostream& operator<<(ostream& cout, MyInteger& p);
public:
    MyInteger() {
        mNumber = 0;
    }
    //成员函数重载前置++运算符
    MyInteger &operator++() {
        mNumber++;//先进行加1
        return *this;//再将自身返回,所以返回类型为MyInteger,返回引用是为了一直对一个数据进行递增操作 
    }

    //成员函数重载后置++运算符
    MyInteger operator++(int) {
        //1、先记录当时的结果
        MyInteger temp = *this;

        //2、递增
        mNumber++;

        //3、返回记录的结果
        return temp;

    } 
private:
    int mNumber;
};

//重载左移运算符
ostream& operator<<(ostream& cout, MyInteger& p) {
    cout << p.mNumber;
    return cout;
}
void test01() {
    MyInteger myInt;
    cout << ++myInt << endl;
}
void test02() {
    MyInteger myInt;
    cout << myInt++ << endl;
}
int main() {

    test02();
    return 0;
}

我以为是前置和后置的函数冲突了就把前置重载给注释了,可还是报错,我猜问题是在左移运算符重载代码中
怎么修改可以让test02中的cout不报错那

  • 写回答

1条回答 默认 最新

  • Huazie 全栈领域优质创作者 2023-01-06 23:21
    关注
    • 把 重载<< 的参数里 的& 去掉

    img

    
    #include <iostream>
    #include <string>
    using namespace std;
    
    class MyInteger {
        friend ostream& operator<<(ostream& cout, MyInteger p);
    public:
        MyInteger() {
            mNumber = 0;
        }
        //成员函数重载前置++运算符
        MyInteger &operator++() {
            mNumber++;//先进行加1
            return *this;//再将自身返回,所以返回类型为MyInteger,返回引用是为了一直对一个数据进行递增操作 
        }
     
        //成员函数重载后置++运算符
        MyInteger operator++(int) {
            //1、先记录当时的结果
            MyInteger temp = *this;
            //2、递增
            mNumber++;
            //3、返回记录的结果
            return temp;
        } 
    
    private:
        int mNumber;
    };
     
    //重载左移运算符
    ostream& operator<<(ostream& cout, MyInteger p) {
        cout << p.mNumber;
        return cout;
    }
    
    void test01() {
        MyInteger myInt;
        cout << ++myInt << endl;
    }
    void test02() {
        MyInteger myInt;
        cout << myInt++ << endl;
    }
    int main() {
        test02();
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月15日
  • 已采纳回答 1月7日
  • 创建了问题 1月6日

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了