少用后置++/--吧骚年

小记一次操作符,方便日后回顾。

#include<ostream>
#include <iostream>
using namespace std;
class MyInt
{
    //全局友元函数
    friend  ostream& operator<<(ostream& o, MyInt myint);
  
   
    int num;
public:
    MyInt() :num(0){};
    //++前置
    MyInt& operator++()
    {
        num++;
        return *this;
    }
    //--前置
    MyInt& operator--()
    {
        num--;
        return *this;
    }
    //后置++
    //后置不能引用是因为变量在栈区,函数用完即销毁,故值传递
    //此处int为占位符,下同
    MyInt operator++(int)
    {
        MyInt temp = *this;
        num++;
        return temp;
    }
    //后置--
    MyInt operator--(int)
    {
        MyInt temp = *this;
        num--;
        return temp;
    }
};
/*
*注意!
*必须采用值传递以兼容前置和后置操作,因为后置操作的匿名变量会立即销毁
*为了安全和性能尽量少用后置操作
*/
ostream&  operator<<(ostream  &o, MyInt myint)
{
    return o<<myint.num;
}

int main()
{
    MyInt m_int;
    cout<< --m_int<<endl;//-1
    cout<< ++m_int << endl;//0

    cout << ++(++m_int) << endl;//2 链式编程
    cout << --(--m_int) << endl;//0 链式编程

    cout << m_int++ << endl;//0
    cout << m_int-- << endl;//1

    cout << "现在的m_int:" << m_int << endl;
    //现在的m_int:0
    cout << (m_int++)++ << endl;
    //1 因为我们只是第一次对num操作了,第二次对一个匿名变量操作了++
    cout << (m_int++, m_int++) << endl;
    //2 因为逗号运算符,每次都对m_int操作
    cout << "现在的m_int:" << m_int << endl;//3
    return 0;
}

因此,尽量少用后置++,除非必要!谢谢观看!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是重载运算符++和--的Complex类的实现代码: ```c++ #include <iostream> using namespace std; class Complex { private: double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} Complex& operator++(); // 前置++ Complex operator++(int); // 后置++ Complex& operator--(); // 前置-- Complex operator--(int); // 后置-- void show() const { cout << "(" << real << ", " << imag << ")" << endl; } }; Complex& Complex::operator++() { real++; return *this; } Complex Complex::operator++(int) { Complex temp(*this); real++; return temp; } Complex& Complex::operator--() { real--; return *this; } Complex Complex::operator--(int) { Complex temp(*this); real--; return temp; } int main() { Complex a(1, 2); (++a).show(); // 输出:(2, 2) a.show(); // 输出:(2, 2) (a++).show(); // 输出:(2, 2) a.show(); // 输出:(3, 2) (--a).show(); // 输出:(2, 2) a.show(); // 输出:(2, 2) (a--).show(); // 输出:(2, 2) a.show(); // 输出:(1, 2) (a--).show(); // 输出:(1, 2) a.show(); // 输出:(0, 2) return 0; } ``` 在上面的代码中,我们为Complex类重载了运算符++和--,包括前置++后置++、前置--和后置--。对于前置++和前置--,我们直接修改实部real的值,并返回*this的引用;对于后置++后置--,我们先用*this的值初始化一个临时对象temp,然后再修改实部real的值,并返回这个临时对象temp,从而实现后置++后置--。在主程序中,我们对Complex对象a进行了多次++和--运算,并输出了运算结果,验证了运算符的正确性。注意,由于后置++后置--返回的是临时对象,因此如果直接调用a--.show(),则不能正确输出a--的结果,必须使用(a--).show()的形式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值