前置后置运算符重载

前置和后置自增

自己实现int类型 MyInteger

内部维护以int数据

MyInteger myInt

myInt ++ 后置  ++myInt  前置

重载++运算符 operator++() 前置   operator++(int) 后置

前置理念 先++ 后返回自身   后置理念 先保存住原有值  内部++ 返回临时数据

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class MyInteger
{
public:
    MyInteger()
    {
        this->m_Num = 0;
    }
    //前置++重载
    MyInteger& operator++()
    {
        this->m_Num++;
        return *this;
    }
    //后置++ 重载
    MyInteger operator++(int)
    {
        //先保存目前数据
        MyInteger tmp = *this;
        this->m_Num++;
        return tmp;
    }
    int m_Num;
};
ostream& operator<<(ostream& cout, MyInteger& myInt)
{
    cout << myInt.m_Num;
    return cout;
}

void test()
{
    MyInteger myint;
    cout << ++myint << endl;        //前置++
    //myint++; //myint++可以执行
    cout << myint++ << endl;        //后置++   VS2019报错 找不到匹配的<<运算符
}

int main()
{
    test();
    system("Pause");
    return 0;
}

 所以,调用代码时候,要优先使用前缀形式,除非确实需要后缀形式返回的原值,前缀和后缀形式语义上是等价的,输入工作量也相当,只是效率经常会略高一些,由于前缀形式少创建了一个临时对象。

补充:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class MyInteger
{
public:
    MyInteger()
    {
        this->m_Num = 0;
    }
    //前置++重载
    MyInteger& operator++()             //前置返回的是引用 是对象本身
    {
        this->m_Num++;
        return *this;
    }
    //后置++ 重载
    MyInteger operator++(int)           //后置返回的是值,拷贝的对象本身的值 即返回的是临时数据
    {
        //先保存目前数据
        MyInteger tmp = *this;
        this->m_Num++;
        return tmp;
    }
    int m_Num;
};
ostream& operator<<(ostream& cout, MyInteger& myInt)
{
    cout << myInt.m_Num;
    return cout;
}

void test()
{
    MyInteger myint;
    //cout << ++myint << endl;        //前置++
    //myint++; //myint++可以执行
    //cout << myint++ << endl;        //后置++   VS2019报错 找不到匹配的<<运算符

    cout << ++(++myint) << endl;    //第一次++myint返回值为1 ++1 即为2 但如果前置重载返回的是值不是引用,那么此时的m_Num是1,而不是2
                                    //只有当前置返回的是对象本身,即是引用的话 m_Num的值才真为2

}

int main()
{
    test();
    system("Pause");
    return 0;
}