第25讲运算符重载.ppt
文本预览下载声明
* * The Lecturer:姚雅鹃 E-mail:kareny@mail.hzau.edu.cn 第二十五讲 运算符重载 运算符重载 重载赋值运算符 重载++、--运算符 对象类型转换 引例 class Complex { …… comolex add(Complex c); …… }; …… Complex ob1, ob2, sum; …… sum=ob1.add(ob2); 能否直观地写成sum=ob1+ob2; 一、运算符重载 通过定义运算符函数,使得已有的运算符能适应新的数据类型。 定义格式: 函数类型 operator重载运算符(形参表) { 函数体 } operator P275 注意 1°只能重载已有运算符,不可臆造新的运算符。 2°不允许改变运算符的优先级和结合性。 3°不允许改变运算符的语法结构。 一、运算符重载 运算符函数作为类的成员函数,若重载的是单目运算符,函数无参数;若重载的是双目运算符,函数只需要一个参数。 一、运算符重载 #includeiostream using namespace std; class Complex { private: double real, imag; public: void set(double r=0, double i=0); void show(); Complex operator+ (const Complex c); Complex operator+ (double r); Complex operator- (const Complex c); Complex operator- (double r); Complex operator* (const Complex c); Complex operator/ (const Complex c); Complex operator+ (); Complex operator- (); }; e.g.25_1 定义复数类实现复数运算。 void Complex:: set( double r, double i ) { real=r; imag=i; } void Complex:: show() { coutreal; if (!imag) { coutendl; return; } if (imag0) cout+; coutimagiendl; } Complex Complex:: operator+(const Complex c) { Complex t; t.real=real+c.real; t.imag=imag+c.imag; return t; } Complex Complex:: operator+(double r) { Complex t; t.real=real+r; t.imag=imag; return t; } Complex Complex:: operator-(const Complex c) { …… } Complex Complex:: operator-(double r) { …… } Complex Complex:: operator*(const Complex c) { …… } Complex Complex:: operator/(const Complex c) { …… } Complex Complex:: operator+() { return *this; } Complex Complex:: operator-() { Complex t; t.real=-real; t.imag=-imag; return t; } void main() { Complex x, y, s; x.set(1, 3); y.set(-5,10); s=x+y; //编译器将
显示全部