Implementación de ++ i e i ++ (simulación de clase personalizada MyInt)

Lunes 22 de febrero de 2021, hace buen tiempo [No lamente el pasado, no desperdicie el presente, no le tema al futuro]


Utilice la clase MyInt para implementar ++ i e i ++.

class MyInt{
    
    
public:
    int value;              //实际的value值
    MyInt(int value){
    
           //方便初始化:MyInt i = 0;
        this->value = value;
    }
    
    /**
     * 重写前置式++运算符(++i时会自动调用本函数)
     * @return 前置式运算会返回当前对象的引用
     */
    MyInt& operator++(){
    
    
        *this += 1; //自加1
        return *this;
    }
    
    /**
     * 重写后置式++运算符(i++时会自动调用本函数)
     * 注意:由于函数重载是以参数类型来区分的,而前置、后置运算又都没有参数。为了解决这个语言学上的漏洞,
     * 只好让后置式运算符有一个int类型的参数(调用时,编译器会默默地为这个int型参数指定0值)
     * @return 返回一个const类型的对象
     */
    const MyInt operator++(int){
    
    
        MyInt oldValue = *this; //取出当前对象
        ++(*this);              //累加(调用上面的前置++的重载函数)
        return oldValue;        //返回先前被取出的值
    }

    /**
     * 重载运算符+=,方便赋值操作:*this += 1;
     */
    MyInt& operator+=(int value){
    
    
        this->value = this->value + value;
        return *this;
    }

    //MyInt& operator--();        //前置式--的实现与上面类似
    //const MyInt operator--(int);   //后置式--的实现与上面类似
 };

referencias

Discusión sobre el mecanismo de realización de ++ i e i ++ en C / C ++

Supongo que te gusta

Origin blog.csdn.net/m0_37433111/article/details/113932876
Recomendado
Clasificación