1、单击此处编辑母版标题样式单击此处编辑母版副标题样式* 1C+语言程序设计 杨国兴 张东玲 彭涛中国水利水电出版社单击此处编辑母版标题样式单击此处编辑母版副标题样式* 2第 6章 多态性 6.1 运算符重载 6.2 运算符重载为类的成员函数 6.3 运算符重载为类的友元函数 6.4 虚函数单击此处编辑母版标题样式单击此处编辑母版副标题样式* 36.1 运算符重载 6.1.1 问题的提出 例 4.3的复数类 #include “iostream.h“ class CComplex private: double real; double imag; public: CComplex(double
2、r, double i); void Print(); CComplex Add(CComplex c); CComplex Sub(CComplex c); ; 第 6章 多态性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;
3、return temp; 单击此处编辑母版标题样式单击此处编辑母版副标题样式* 46.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 Draw(); 第 6章 多态性程序运行结果为:程序运行结果为:Draw a Shape. The color is RedDraw a Shape. The color is GreenDraw a Shape. The color is Red Black 虽然父类的指针可以指向子类的对象,
4、但调用的函数 Draw()都是父类 CShape的成员函数 为了能通过基类的指针调用派生类的成员函数,可以使用虚函数的方法,即把成员函数 Draw()声明为虚函数。例 6.7 用虚函数实现动态多态#include #include using namespace std;class CPointprivate:int X;int Y;public:CPoint(int x=0, int y=0)X=x;Y=y;CPoint(CPoint Y=p.Y;int GetX()return X;int GetY()return Y;第 6章 多态性例 6.7 (续一)class CShapeprivate:char Color10;public:CShape(char *c)strcpy(Color,c);virtual void Draw()cout “Draw a Shape. The color is “ Color endl;void PrintColor()cout Color endl;第 6章 多态性