复数类重载两个类运算符 include <iostream.h> class complex( private float real,∥/实部 Imag ∥虚部 publi complex( float=0, float 1=0) real=r, imag =1, void printo cout<<" c(<<real I I <<imag << endl
11 复数类重载两个类运算符 # include <iostream.h> class complex{ private: float real, // 实部 imag; // 虚部 public: complex(float r = 0, float i = 0) { real = r; imag = i; } void print() { cout << "c(" << real << ',' << imag << ')' << endl; } };
成员函数方式 少+(a)对单目减 complex/返回类型1 complex类名: operator() { return complex( real, imag) 々(b)对双目加: 0mpex返回类型 complex/类名+ operater( complex&c) com float r= this real +c real float i= this - imag c imag return complex(r, i);∥返回一个新对象这时将调用构造函数 12
12 成员函数方式 (a)对单目减: complex /*返回类型*/ complex /*类名*/ :: operator-( ) { return complex(-real,-imag); } (b)对双目加: complex /*返回类型*/ complex /*类名*/ :: opelater+ ( complex &c ) { float r = this -> real + c.real; float i = this -> imag + c.imag; return complex(r,i); // 返回一个新对象,这时将调用构造函数 }
友元函数方式 k(a)友元函数方式的双目+的重载定义 complex operator+(complex &c1, complex &c2 float =cl real c2, real- float i=c1 imag c2 imag; return complex(r, 1; 改这时,要在类 complex定义中增加友元函数声明 riend complex operator+( complex & complex 妆(b)对单目减 complex operator(complex&c) return complex(· c real,“ CImag); 13
13 友元函数方式 (a)友元函数方式的双目+的重载定义 complex operator+ ( complex & c1, complex & c2 ) { float r = c1.real + c2.real; float i = c1.imag + c2.imag; return complex( r, i ); } 这时,要在类complex定义中增加友元函数声明 friend complex operator+ ( complex &, complex & ); (b)对单目减: complex operator- ( complex & c ) { return complex( - c.real, - c.imag ); }
对象赋值与赋值运算符重载 ↓赋值是一种极为普通的运算。当运算对象 不是基本类型时,应当给出运算符重载函 数。这时,两个同类对象之间的相互赋值 是逐个数据成员赋值。当赋值符重载函数 缺省时,C++编译器可以为每个类生成一 个缺省的赋值运算符重载函数 这种类对象的赋值,不需程序员自己去定 义赋值号的重载函数,便可以自由地使用 赋值号去实现同类对象间的赋值 14
14 对象赋值与赋值运算符重载 赋值是一种极为普通的运算。当运算对象 不是基本类型时,应当给出运算符重载函 数。这时,两个同类对象之间的相互赋值 是逐个数据成员赋值。当赋值符重载函数 缺省时,C++编译器可以为每个类生成一 个缺省的赋值运算符重载函数 这种类对象的赋值,不需程序员自己去定 义赋值号的重载函数,便可以自由地使用 赋值号去实现同类对象间的赋值
类型转换与转换函数 在对表达式求值时,可能对操作对象进行 类型转换。同样,一个类对象运算的表达 式中也存在类型转换问题 转换有两种 由其它类型转换为本类类型; 本类类型转换为其它类型 15
15 类型转换与转换函数 在对表达式求值时,可能对操作对象进行 类型转换。同样,一个类对象运算的表达 式中也存在类型转换问题 转换有两种: ·由其它类型转换为本类类型; ·本类类型转换为其它类型