C++重载递减运算符问题解决

学习递增运算符之后,自己写递减运算符,然后写完后置递减,发现一直报错然后查百度,发现是左移运算符需要加const

错误

在这里插入图片描述

解决办法

将const加入到左移的第二个参数,如果使用友元,同样添加;

// 友元
friend ostream &operator<<(ostream &cout, const MyInter(类名称) &p);
// 全局函数
ostream &operator<<(ostream &cout, const MyInter &p)

原因:使用cout为了不能改变类的属性,必须加const
以下为修改后代码:

/*
    author:ivarnd;
    time:2022/8/21;
    功能:重载递减运算符
*/
#include<iostream>
#include<string>
using namespace std;

class MyInter{
    // 友元
    friend ostream &operator<<(ostream &cout, const MyInter &p);

    public:
        MyInter()
        {
            m_int = 0;
        }
        /*
            前置和后置的不同:
                前置递增返回引用 后置递增返回值(temp是临时变量 用完就要被释放)
        */
        // 前置递减
        MyInter &operator--()
        {
            // 先进行++运算
            m_int--;
            // 在将自身返回
            return *this;
        }
        // 后置递减返回值
        // operator--(int), int代表占位符,用于区分前置递减和后置递减
        MyInter operator--(int)
        {
            MyInter temp = *this; // 记录当前值
            m_int--; // 进行递减操作
            return temp; // 将记录结果做返回
        }

    private:
        int m_int;
};

// 左移运算符
// 需要加入const
ostream &operator<<(ostream &cout, const MyInter &p)
{
    cout << p.m_int;
    return cout;
}

void test01()
{
    MyInter myint;
    cout << --myint << endl;
    cout << myint << endl;

}
void test02()
{
    MyInter myint;
    cout << myint-- << endl;
    cout << myint << endl;
}

int main()
{
    test02();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值