c++重载后置++和--


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 }

同样的思路在==和!=中也会用到(善于利用现有资源)^_^。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM