Complex operator +(const Complex&c1 const Complex&c2) return Complex(c1.real+c2.real,c1.imag+c2.imag); Complex operator +(const Complex&c,double d) return Complex(c.real+d,c.imag); } Complex operator +(double d,const Complex&c) /这个只能作为全局函数重载。为什么? return Complex(d+c.real,c.imag); Complex a(1,2),b(3,4),c1,c2,c3; c1 a b; c2=b+21.5 c3=10.2+a;
Complex operator + (const Complex& c1, const Complex& c2) { return Complex(c1.real+c2.real,c1.imag+c2.imag); } Complex operator + (const Complex& c, double d) { return Complex(c.real+d,c.imag); } Complex operator + (double d, const Complex& c) //这个只能作为全局函数重载。为什么? { return Complex(d+c.real,c.imag); } ...... Complex a(1,2),b(3,4),c1,c2,c3; c1 = a + b; c2 = b + 21.5; c3 = 10.2 + a;
单目操作符重载 ·作为成员函数重载 ·定义格式 class<类名> { <返回值类型>operator#(); } <返回值类型><类名>:operator#(){..} 使用格式 <类名>a; 井a 或, a.operator#(
◼ 作为成员函数重载 • 定义格式 class <类名> {...... <返回值类型> operator # (); }; <返回值类型> <类名>::operator # () { ...... } • 使用格式 <类名> a; #a 或, a.operator#() 单目操作符重载
例:实现复数的取负操作 class Complex public: Complex operator -(const Complex temp; temp .real -real; temp.imag -imag; return temp; }; Complex a(1,2),b; b三-a;/把b修改成a的负数
例:实现复数的取负操作 class Complex { ...... public: ...... Complex operator -() const { Complex temp; temp .real = -real; temp.imag = -imag; return temp; } }; ...... Complex a(1,2),b; b = -a; //把b修改成a的负数
单目操作符重载(续1) ·作为全局(友元)函数重载 ·定义格式 <返回值类型>operator#(<类型><参数>){.. ■<类型>必须是类、结构、枚举或它们的引用类型 。使用格式为: <类型>a #a 或 operator#(a)
单目操作符重载(续1) ◼ 作为全局(友元)函数重载 • 定义格式 <返回值类型> operator #(<类型> <参数>) { …... } ◼ <类型>必须是类、结构、枚举或它们的引用类型。 • 使用格式为: <类型> a; #a 或 operator#(a)
例:实现判断复数为“零”的操作 class Complex public: friend bool operator !(const Complex &c); } bool operator !(const Complex &c) return (c.real ==0.0)&&(c.imag =0.0); Complex a(1,2); if(la)/a为0
例:实现判断复数为“零”的操作 class Complex { ...... public: ...... friend bool operator !(const Complex &c); }; bool operator !(const Complex &c) { return (c.real == 0.0) && (c.imag == 0.0); } ...... Complex a(1,2); ...... if (!a) //a为0 ......