运算符重载实际是一个函数,所以运算符的重载实际上是函数的重载。编译程序对运算符重载的选择,遵循着函数重载的选择原则。当遇到不很明显的运算时,编译程序将去寻找参数相匹配的运算符函数。
运算符重载的作用:
运算符重载允许C/C++的运算符在用户定义类型(类)上拥有一个用户定义的意义。重载的运算符是函数调用的语法修饰:
- class Fred
- Fred add(Fred, Fred);
- Fred operator+ (Fred, Fred);
功能相同,只是冲在'+'使得功能更加的直观.
可以用作重载的运算符:
算术运算符:+,-,*,/,%,++,--;
位操作运算符:&,|,~,^,<<,>>
逻辑运算符:!,&&,||;
比较运算符:<,>,>=,<=,==,!=;
赋值运算符:=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=;
其他运算符:[],(),->,,(逗号运算符),new,delete,new[],delete[],->*。
下列运算符不允许重载:
.,.*,::,?:
1. 重载为类的成员函数
- class complex
- complex operator +(const complex &c);
- inline complex complex::operator +(const complex &c)
- {
- return complex(real + c.real, imag + c.imag);
- }
程序中出现的表达式:
c1+c2
编译程序将给解释为:
c1.operator+(c2)
其中,c1和c2是complex类的对象。operator+()是运算+的重载函数。
重载为成员函数时,不能再显式说明参数。重载为成员函数时,总时隐含了一个参数,该参数是this指针。this指针是指向调用该成员函数对象的指针。
2. 重载为友元函数:
运算符重载函数还可以为友元函数。当重载友元函数时,将没有隐含的参数this指针。这样,对双目运算符,友元函数有2个参数,对单目运算符,友元函数有一个参数。但是,有些运行符不能重载为友元函数,它们是:=,(),[]和->。
- friend complex operator +(const complex &c1, const complex &c2);
- complex operator +(const complex &c1, const complex &c2)
- {
- return complex(c1.real + c2.real, c1.imag + c2.imag);
- }
该程序的运行结果与上例相同。前面已讲过,对又目运算符,重载为成员函数时,仅一个参数,另一个被隐含;重载为友元函数时,有两个参数,没有隐含参数。因此,程序中出现的 c1+c2
编译程序解释为:
operator+(c1, c2)
3. 两种重载形式的比较
一般说来,单目运算符最好被重载为成员;对双目运算符最好被重载为友元函数,双目运算符重载为友元函数比重载为成员函数更方便此,但是,有的双目运算符还是重载为成员函数为好,例如,赋值运算符。因为,它如果被重载为友元函数,将会出现与赋值语义不一致的地方。
- counter operator ++();
- counter operator ++(int );
- counter counter::operator ++()
- {
- v++;
- return *this;
- }
- counter counter::operator ++(int)
- {
- counter t;
- t.v = v++;
- return t;
- }
4. 重载函数调用运算符
可以将函数调用运算符()看成是下标运算[]的扩展。函数调用运算符可以带0个至多个参数。下面通过一个实例来熟悉函数调用运算符的重载.
- class F
- {
- double operator ()(double x, double y) const;
- };
- double F::operator ()(double x, double y) const
- {
- return (x+5)*y;
- }
- void main()
- {
- F f;
- cout<<f(1.5, 2.2)<<endl;
- }
5.重载输出运算符 <<
下面是一个栈类的输出 cout<<st;为输出整个栈的元素
- friend ostream& operator<<(ostream &os ,const CSTAC &st);
- ostream& operator<<(ostream &os ,const CSTAC &st)//CSTAC::
- {
- if (st.count == 0)
- {
- os<<"the stack is empty!"<<endl;
- }
- for (int i=0; i<st.count; i++)
- {
- os<<st.p[i]<<" ";
- }
- os<<endl;
- return os;
- }
OVER