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