单目运算符的重载
Ending… 谢谢
//等价于d operator++(0); //等价于d operator++(); //等价于 operator--(d,0); //等价于 operator--(d);
输出结果: 5,6,7,7 7,6,5,5
#include<iostream.h> class counter { unsigned int value; public: counter() {value=o;} void operator++(); //前缀方式重载 void operator--(); //前缀方式重载 unsigned int operator()(); }; void counter::operator++() { If(value<8) value++; } Void counter::operator--() { If(value>6) value--; } unsigned int counter::operator()() { return value; }
单目运算符的重载
万军 通信1403 31402145
单目运算符只有一个操作符,如!a,-b,&c,*p,还有最常 用的++i和--i等。重载单目运算符的方法与重载双目运算符 的方法是类似的。但由于单目运算符只有一个操作数,因此 运算符重载函数只有一个参数,如果运算符重载函数作为成 员函数,则还可省略此参数。
单目运算符的重载
单目运算符只有一个操作符,在这里,我们只介绍自加++和自减--运算符。 ++,--运算符有前置,后置之分 前置运算符作为一元运算符重载
1.重载为成员函数: T operator++(); T operator--(); 2.重载为友元函数: T operator++(T); T operator--(T);
单目运算符的重载
后置运算符作为二元运算符重载 多写一个参数,具体无意义 1.重载为成员函数: T operator++(int); T operator--(int); 2.重载为友元函数: T operator++(T,int); T operator--(T,int);
以重载+说,单目运算符最好被重载为成员函数;对双目运算符最好被重载友元 函数。 前置单目运算符重载为类的成员函数时,不需要显式说明参数,即 函数没有形参。 后置单目运算符重载为类的成员函数时,函数要带有一个整型形参。 用成员函数实现运算符的重载时,运算符的左操作数为当前对象, 并且要用到隐含的this指针。运算符重载函数不能定义为静态的成员函 数,因为静态的成员函数中没有this指针
在程序中对运算符“++”进行了 重载,使它能用于Time类对象.
例1
Int main(){ cdemo d(5); cout << (d++) << “ , ”; cout << d << “ , ”; cout << (++d) <<“ , ”; cout << d << endl; cout << (d--) << “ , ”; cout << d << “ , ”; cout << (--d) <<“ , ”; cout << d << endl; return 0; }
成员函数重载
前缀式 后缀式 对象.operator++() 对象.operator++(int)
友元函数重载
operator++(类&对象) operator++(类&对象,int)
下面以自增运算符”++“为例,介绍单目运算符的重载 例:有一个Time类,包含数据成员minute(分)和sec(秒),模拟秒表,每次走一秒,满 60秒进一分钟,此时秒又从0开始算。要求输出分和秒的值。
main() { counter my_counter; for(int i=0;i<12;i++) { ++my_counter; cout<<“\n my_counter=”<<my_counter(); } --my_counter; --my_counter; --my_counter; cout<<“\n my_counter=”<<my_counter(); return0; }