详解C++编程中一元运算符的重载
可重载的一元运算符如下:
- !(逻辑“非”)
- &(取址)
- ~(二进制反码)
- *(取消指针引用)
- +(一元加)
- -(一元求反)
- ++(递增)
- --(递减)
- 转换运算符
后缀递增和递减运算符(++和––)在递增和递减中单独处理,下面会讲到。
以下规则适用于所有其他一元运算符。若要将一元运算符函数声明为非静态成员,则必须用以下形式声明它:
ret-typeoperatorop()
其中ret-type是返回类型,op是上表中列出的运算符之一。
若要将一元运算符函数声明为全局函数,则必须用以下形式声明它:
ret-typeoperatorop(arg)
其中ret-type和op如上所述用于成员运算符函数,arg是要参与运算的类类型的参数。
注意
一元运算符的返回类型没有限制。例如,逻辑“非”(!)返回整数值是合理的,但并非强制性的。
递增和递减运算符重载
由于递增和递减运算符各有两个变量,因此它们属于一个特殊类别:
- 前置递增和后置递增
- 前置递减和后置递减
编写重载的运算符函数时,为这些运算符的前缀和后缀版本实现单独的版本很有用。若要区分这两者,请遵循以下规则:运算符的前缀形式与声明任何其他一元运算符的方式完全相同;后缀形式接受int类型的其他参数。
注意
当为递增或递减运算符的前缀形式指定重载运算符时,其他参数的类型必须是int;指定任何其他类型都将产生错误。
以下示例显示如何为Point类定义前缀和后缀递增和递减运算符:
//increment_and_decrement1.cpp classPoint { public: //Declareprefixandpostfixincrementoperators. Point&operator++();//Prefixincrementoperator. Pointoperator++(int);//Postfixincrementoperator. //Declareprefixandpostfixdecrementoperators. Point&operator--();//Prefixdecrementoperator. Pointoperator--(int);//Postfixdecrementoperator. //Definedefaultconstructor. Point(){_x=_y=0;} //Defineaccessorfunctions. intx(){return_x;} inty(){return_y;} private: int_x,_y; }; //Defineprefixincrementoperator. Point&Point::operator++() { _x++; _y++; return*this; } //Definepostfixincrementoperator. PointPoint::operator++(int) { Pointtemp=*this; ++*this; returntemp; } //Defineprefixdecrementoperator. Point&Point::operator--() { _x--; _y--; return*this; } //Definepostfixdecrementoperator. PointPoint::operator--(int) { Pointtemp=*this; --*this; returntemp; } intmain() { }
可使用以下函数头在文件范围中(全局)定义同一运算符:
friendPoint&operator++(Point&)//Prefixincrement friendPoint&operator++(Point&,int)//Postfixincrement friendPoint&operator--(Point&)//Prefixdecrement friendPoint&operator--(Point&,int)//Postfixdecrement
表示递增或递减运算符的后缀形式的int类型的参数不常用于传递参数。它通常包含值0。但是,可按以下方式使用它:
//increment_and_decrement2.cpp classInt { public: Int&operator++(intn); private: int_i; }; Int&Int::operator++(intn) { if(n!=0)//Handlecasewhereanargumentispassed. _i+=n; else _i++;//Handlecasewherenoargumentispassed. return*this; } intmain() { Inti; i.operator++(25);//Incrementby25. }
除显式调用之外,没有针对使用递增或递减运算符来传递这些值的语法,如前面的代码所示。实现此功能的更直接的方法是重载加法/赋值运算符(+=)。