收藏 分享(赏)

第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt

上传人:11xg27ws 文档编号:4725160 上传时间:2019-01-09 格式:PPT 页数:46 大小:242KB
下载 相关 举报
第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt_第1页
第1页 / 共46页
第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt_第2页
第2页 / 共46页
第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt_第3页
第3页 / 共46页
第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt_第4页
第4页 / 共46页
第6章+《C++程序设计教程与实验指导》-杨国兴+++多态性.ppt_第5页
第5页 / 共46页
点击查看更多>>
资源描述

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章 多态性

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 实用文档 > 简明教程

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报