第8章多态性 8.1运算符重载 82运算符重载为类的成员函数 83运算符重载为类的友元函数 84虚函数
第8章 多态性 8.1 运算符重载 8.2 运算符重载为类的成员函数 8.3 运算符重载为类的友元函数 8.4 虚函数
第8章多态性 8.1运算符重载 81.1问题的提出 例6.3的复数类 CComplex CComplex: Add(ccomplex c) include iostream h class CComplex CComplex temp; private: temp real real + c real; double real; temp imag imag C imag; double imag return temp; public CComplex(double r, double i);i CComplex CComplex: Sub(CComplex c) void print(; CComplex Add (ccomplex c); CComplex temp; cComplex Sub(CComplex c); temp. real real -C real; temp imag imag-C imag; return temp;
8.1 运算符重载 8.1.1 问题的提出 例6.3的复数类 #include "iostream.h" class CComplex { private: double real; double imag; public: CComplex(double r, double i); void Print(); CComplex Add(CComplex c); CComplex Sub(CComplex c); }; 第8章 多态性 CComplex CComplex::Add(CComplex c) { CComplex temp; temp.real = real + c.real; temp.imag = imag + c.imag; return temp; } CComplex CComplex::Sub(CComplex c) { CComplex temp; temp.real = real - c.real; temp.imag = imag - c.imag; return temp; }
第8章多态性 8.1运算符重载 81.1问题的提出(续一) void main(void) CComplex a(1, 2),b(3.0,4.0),c, d C=a.Add(b; d =a sub(b); cout≤<"c="; 复数加减法只能调用成员函数实现, 不能使用符号“+”和“”,可以通 C Print(; 过重载“+”、“-”运算符,实现如 cout <<"d=w c≡a+b这样的调用方式 d Print(; 运算符重载:运算符重载的实质就是对已有的运算符赋予多重含义,使同一个运算符 作用于不同类型的数据时,产生不同的行为。运算符重载的实质就是函数重载
8.1 运算符重载 8.1.1 问题的提出(续一) void main(void) { CComplex a(1, 2), b(3.0, 4.0), c,d; c = a.Add(b); d = a.Sub(b); cout << "c = "; c.Print(); cout << "d = "; d.Print(); } 第8章 多态性 复数加减法只能调用成员函数实现, 不能使用符号“+”和“-”,可以通 过重载“+”、“-”运算符,实现如 c=a+b这样的调用方式 运算符重载:运算符重载的实质就是对已有的运算符赋予多重含义,使同一个运算符 作用于不同类型的数据时,产生不同的行为。运算符重载的实质就是函数重载
第8章多态性 例8.1用运算符实现复数的加减运算 include"iostream h class CComplex private: double real: double imag public CComplex(double r=0, double i=o) void Printo CComplex operator +(CComplex c) CComplex operator-(CComplex c) CComplex: CComplex (double r, double i eal=r Imag=I
例8.1 用运算符实现复数的加减运算 #include "iostream.h" class CComplex { private: double real; double imag; public: CComplex(double r=0, double i=0); void Print(); CComplex operator +(CComplex c); CComplex operator -(CComplex c); }; CComplex::CComplex (double r, double i) { real = r; imag = i; } 第8章 多态性
第8章多态性 例8.1(续一) void CComplex. Printo cout≤<"("<srea<<","<<imag≤")"<<endl; CComplex CComplex:: operator +(CComplex c) CComplex temp temp. real real c real temp. imag= imag c imag return temp; CComplex CComplex operator-(CComplex c) CComplex temp H temp. real=real-creal temp. imag= imag -C imag turn temp
例8.1 (续一) void CComplex::Print() { cout << "(" << real << "," << imag << ")" << endl; } CComplex CComplex::operator +(CComplex c) { CComplex temp; temp.real = real + c.real; temp.imag = imag + c.imag; return temp; } CComplex CComplex::operator -(CComplex c) { CComplex temp; temp.real = real - c.real; temp.imag = imag - c.imag; return temp; } 第8章 多态性