C++中自增和自减的实现

C++中自增和自减符号我们经常使用,了解它的实现方式能够更好的为自己定义的类实现自增和自减。我们首先需要了解一个知识点,自增和自减是通过重载"++"和"--"来实现的,但是普通的重载形式无法区分这两种情况,为了解决这个情况,后置版本接受一个额外的(不被使用)int类型的形参,编译器为这个形参提供一个值为0的实参

#include <iostream>
using namespace std;

class Test{
    int a;
    string str;
public:
    Test(int i, string s) : a(i), str(std::move(s)) {}

    Test &operator++(){//前置++
        ++a;
        return *this;
    }

    Test operator++(int){ //后置++,因为此处要返回局部变量,故不能使用引用
        Test ret = *this;
        ++*this;
        return ret;
    }

    Test &operator--(){//前置--
        --a;
        return *this;
    }

    Test operator--(int){ //后置--,因为此处要返回局部变量,故不能使用引用
        Test ret = *this;
        --*this;
        return ret;
    }

    friend ostream& operator<<(ostream &os, const Test &test){
        os << test.str << " : " << test.a << endl;
        return os;
    }
};

int main(){
    Test test(1, "C++");
    cout << test << endl;
    cout << "前置自增 : " << ++test << endl;
    cout << test++ << endl;
    cout << "后置自增 : " << test << endl;
    cout << "前置自减 : " << --test << endl;
    cout << test-- << endl;
    cout << "后置自减 : " << test << endl;
    return 0;
}

输出:

C++ : 1

前置自增 : C++ : 2

C++ : 2

后置自增 : C++ : 3

前置自减 : C++ : 2

C++ : 2

后置自减 : C++ : 1

猜你喜欢

转载自www.cnblogs.com/raysuner/p/12273136.html