重载自增自减运算符

版权声明:本文为博主原创文章,欢迎转载,请标明出处。 https://blog.csdn.net/Think88666/article/details/86585123
class Test{
public:
    int val;
    Test(int val){
        this->val = val;
    }
    Test(const Test&copy){
        this->val = copy.val;
    }
    //前置++
    Test& operator ++(){
        ++this->val;
        return *this;
    }
    //后置++

    Test operator ++(int){
        Test b = *this;
        this->val++;
        return b;
    }
    //前置--
    Test operator--(int){
        Test temp = *this;
        this->val--;
        return temp;
    }

    //后置--
    Test& operator --(){
        this->val--;
        return *this;
    }
};

记住一点,前置运算返回自身的引用,后置运算返回临时变量的拷贝

猜你喜欢

转载自blog.csdn.net/Think88666/article/details/86585123