一般情况下,操作符既可以作为全局函数 也可以作为成员函数来重载 在有些情况下,操作符只能作为全局函数 或只能作为成员函数来重载!
◼ 一般情况下,操作符既可以作为全局函数, 也可以作为成员函数来重载。 ◼ 在有些情况下,操作符只能作为全局函数 或只能作为成员函数来重载!
双目操作符重载 ■作为成员函数重载 。定义格式 class<类名> { <返回值类型>operator#(<类型>);/#代表可重载的操作符 7 <返回值类型><类名>:operator#(<类型><参数>){...} 使用格式 <类名>a; <类型>b; a b 或, a.operator#(b)
双目操作符重载 ◼ 作为成员函数重载 • 定义格式 class <类名> { ...... <返回值类型> operator # (<类型>); //#代表可重载的操作符 }; <返回值类型> <类名>::operator # (<类型> <参数>) { ...... } • 使用格式 <类名> a; <类型> b; a # b 或, a.operator#(b)
例、实现复数的“等于”和“不等于”操作 class Complex double real,imag; public: bool operator ==(const Complex&x)const return (real =x.real)&&(imag =x.imag); bool operator !=(const Complex&x)const return !(*this =x); Complex c1,c2; if (c1 =c2)//if (c1 !c2)
例、实现复数的“等于”和“不等于”操作 class Complex { double real, imag; public: ...... bool operator ==(const Complex& x) const { return (real == x.real) && (imag == x.imag); } bool operator !=(const Complex& x) const { return (real != x.real) || (imag != x.imag); } }; ...... Complex c1,c2; ...... if (c1 == c2) //或 if (c1 != c2) ...... bool operator !=(const Complex& x) const { return !(*this == x); }
双目操作符重(续1) ■作为全局(友元)函数重载载 。定义格式 <返回值类型>operator#(<类型1><参数1> <类型2><参数2>) {} <类型1>和<类型2>中至少应该有一个是类、结构、 枚举或它们的引用类型。 使用格式为: <类型1>a; <类型2>b; a b 或 operator#(a,b)
双目操作符重(续1) ◼ 作为全局(友元)函数重载载 • 定义格式 <返回值类型> operator #(<类型1> <参数1>, <类型2> <参数2>) { …... } ◼ <类型1>和<类型2>中至少应该有一个是类、结构、 枚举或它们的引用类型。 • 使用格式为: <类型1> a; <类型2> b; a # b 或 operator#(a,b)
例:重载操作符+,使其能够实现实数与复数 的混合运算。 class Complex double real,imag; public: Complex()real 0;imag 0; Complex(double r,double i)real r;imag i; friend Complex operator (const Complex&c1, const Complex&c2)月 friend Complex operator +(const Complex&c, double d); friend Complex operator (double d, const Complex&c);
例:重载操作符+,使其能够实现实数与复数 的混合运算。 class Complex { double real, imag; public: Complex() { real = 0; imag = 0; } Complex(double r, double i) { real = r; imag = i; } ...... friend Complex operator + (const Complex& c1, const Complex& c2); friend Complex operator + (const Complex& c, double d); friend Complex operator + (double d, const Complex& c); };