c++語言並不要求遞增和遞減運算符必須是類的成員,但是因為它們改變的正好是所操作對象的狀態,所以建議將其設定為成員函數。(但下面的代碼為了練習,還是分別采用成員函數和全局函數的方式實現)
業余實現代碼:
1 #include<iostream>
2 using namespace std; 3 class Test { 4 friend Test & operator--(Test &obj); 5 friend Test operator--(Test &obj, int); 6 public: 7 Test(int a = 0, int b = 0) 8 { 9 this->a = a; 10 this->b = b; 11 } 12 void display() 13 { 14 cout << "a:" << a << " b:" << b << endl; 15 } 16 public: 17 //前置++
18 Test & operator++() 19 { 20 this->a++; 21 this->b++; 22 return *this; 23 } 24 //后置++
25 Test operator++(int) 26 { 27 Test temp = *this; 28 this->a++; 29 this->b++; 30 return temp; 31 } 32 private: 33 int a; 34 int b; 35 }; 36 //前置--
37 Test & operator--(Test &obj) 38 { 39 obj.a--; 40 obj.b--; 41 return obj; 42 } 43
44 //后置--
45 Test operator--(Test &obj,int) 46 { 47 Test temp = obj; 48 obj.a--; 49 obj.b--; 50 return temp; 51 } 52 int main() 53 { 54 Test t1(1, 2); 55 t1.display(); 56 ++t1; 57 t1.display(); 58 --t1; 59 t1.display(); 60 Test t2(3, 4); 61 t2.display(); 62 t2++; 63 t2.display(); 64 t2--; 65 t2.display(); 66 cout << "hello world!\n"; 67 return 0; 68 }
NOTE:
后置版本接受一個額外的參數(不被使用)int類型的參數(必須是int類型的)。當我們使用后置運算符時,編譯器為這個形參提供一個值為0的實參。盡管從語法上說后置函數可以使用這個額外的形參,但在實際過程中通常不會這樣做。這個形參的唯一作用就是區分前置和后置版本的函數,而不是真的要在實現后置版本是參與運算。因為前置和后置版本的遞增或者遞減函數原型必須加以一個特殊的區分,c++語言選擇增加一個占位參數實現后置版本。
如果我們想要通過函數的方式調用后置版本,則必須為它的整形參數傳遞一個值。
eg:
a.operator++(0);//調用后置版本,經測試,不用0也行,只要可以轉換成int的任意數。
a.operator++();//調用前置版本
專業軟件工程師實現方法:
1 #include<iostream>
2 using namespace std; 3 class Test { 4 friend Test & operator--(Test &obj); 5 friend Test operator--(Test &obj, int); 6 public: 7 Test(int a = 0, int b = 0) 8 { 9 this->a = a; 10 this->b = b; 11 } 12 void display() 13 { 14 cout << "a:" << a << " b:" << b << endl; 15 } 16 public: 17 //前置++
18 Test & operator++() 19 { 20 this->a++; 21 this->b++; 22 return *this; 23 } 24 //后置++
25 Test operator++(int) 26 { 27 Test temp = *this; 28 ++*this; 29 return temp; 30 } 31 private: 32 int a; 33 int b; 34 }; 35 //前置--
36 Test & operator--(Test &obj) 37 { 38 obj.a--; 39 obj.b--; 40 return obj; 41 } 42
43 //后置--
44 Test operator--(Test &obj,int) 45 { 46 Test temp = obj; 47 --obj; 48 return temp; 49 } 50 int main() 51 { 52 Test t1(1, 2); 53 t1.display(); 54 ++t1; 55 t1.display(); 56 --t1; 57 t1.display(); 58 Test t2(3, 4); 59 t2.display(); 60 t2++; 61 t2.display(); 62 t2--; 63 t2.display(); 64 cout << "hello world!\n"; 65 return 0; 66 }
同樣的思路在==和!=中也會用到(善於利用現有資源)^_^。