运算符重载的主要目的是为了让类对象能像普通数据类型一样能够进行加减乘除,自加自减等操作,非常直观方便。现在来回顾C++的自加减(分前置与后置)以及不等号非运算符,赋值运算符的重载。
1 ++重载
(1)前置++运算符的重载方式:
成员函数的重载: 函数类型& operator++()
友元函数的重载:friend 函数类型& operator++(类类型& )
(2)后置++运算符的重载方式:
成员函数的重载:函数类型& operator++(int)
友元函数的重载:friend 函数类型& operator++(类类型&, int)
注意,为了区分前置++与后置++的区别,需要在参数后增加一个"int"以示区分。含有"int"的重载方式为后置++,否则为前置++。前置--与后置--类似用法。前面说过,成员函数与友元函数的重载如果同时存在时,会先调用成员函数的重载,但是在++或--时,成员函数与友元函数的重载是不能同时存在的。
下面举一个例子:
下面是它们的具体代码实现:
关于!及=赋值运算符的重载以String类进行说明:
下面是String类的定义:
下面是具体实现:
针对String类写的一个简单的用例: