1、自加自减运算符重载
自加++、自减- - 运算符可以重载,但有前置和后置之分,用于对象也是如此
2、增加int类型的重载
C++规定,在重载“++”时,允许写一个增加了无用int类型形能的版本,编译器处理“++”“–”前置表达式时,调用参数个数正常的重载函数;处理后置的表达式时,调用多出一个参数的重载函数。
重载的后置运算符的形参表中有一个int 类型的参数,它仅表明重载的是后置运算符,不需要定义形参变量,在函数体中也不必使用它。
3、单目运算符重载
单目运算符“++”重载为类的成员函数,单目运算符“- -”重载为类的友元函数
(1)单目运算符“ ++ ”重载为类的成员函数
#include <iostream>
using namespace std;
class Point//Point 类定义
{
private:
int x, y;
public:
Point(int px=0, int py=0):x (px), y(py) {
}
void print();
Point operator++(); //前缀++运算符重载
Point operator++(int); //后缀++运算符重载
};
void Point::print() //输出
{
cout<<"("<<x<<","<<y<<") "<<endl;
}
Point Point::operator++() //前缀++,先返回++后的值
{
x++;
y++;
return *this;
}
Point Point::operator++(int) //返回++前的值,本身值进行++操作
{
Point old = *this;
x++
y++;
return old;
}
int main()