C程序设计教程与实验指导杨国兴多态性.ppt
文本预览下载声明
C++语言程序设计 杨国兴 张东玲 彭涛 第6章 多态性 6.1 运算符重载 6.2 运算符重载为类的成员函数 6.3 运算符重载为类的友元函数 6.4 虚函数 6.1 运算符重载 6.1.1 问题的提出 例4.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); }; 6.1 运算符重载 6.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(); } 例6.1 用运算符实现复数的加减运算 #include iostream using namespace std; 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; } 例6.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; } 例6.1 (续二) void main(void) { CComplex a(1, 2), b(3.0, 4.0), c,d; c = a+b; d = a-b; cout c = ; c.Print(); cout d = ; d.Print(); } 6.1 运算符重载 6.1.2 运算符重载的格式与规则 1. 运算符重载的格式 运算符重载为类的成员函数 运算符重载为类的友元函数 运算符重载的为类的成员函数,在类中声明的格式为: 函数类型 operator 运算符(参数表); 定义该函数的格式: 函数类型 类名::operator 运算符(参数表) { ?????? 函数体; } 也可以将重载运算符函数的定义直接写在类中。 6.1 运算符重载 6.1.2 运算符重载的格式与规则(续) 2. 运算符重载的规则 (1)除“.”、“*”、“::”、“?:”和“sizeof”等几个运算符不能重载外,C++中几乎所有的运算符都可以重载。 (2)运算符被重载后,其优先级和结合性不会改变。 (3)不能改变运算符操作对象的个数。 6.2 运算符重载为类的成员函数 6.2.1 双目运算符重载 双目运算符,如果重载为类的成员函数,其参数为一个,即比运算对象少一个。 例6.2 复数的乘法运算,在上例的基础上添加乘法运算符重载函数。复数类乘法运算的定义如下: (a+bi)*(x+yi)= a*x-b*y + (a*y + b*x)i 例6.2 复数乘法运算源程序 #include iostream using namespace std; class CComplex { private: double real; double imag; public: CComple
显示全部