c程序设计(part3).ppt

上传人:wuy****n92 文档编号:79014055 上传时间:2023-03-19 格式:PPT 页数:64 大小:366.50KB
返回 下载 相关 举报
c程序设计(part3).ppt_第1页
第1页 / 共64页
c程序设计(part3).ppt_第2页
第2页 / 共64页
点击查看更多>>
资源描述

《c程序设计(part3).ppt》由会员分享,可在线阅读,更多相关《c程序设计(part3).ppt(64页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、面向对象程序设计(part 3)多态n定义n一般含义n某论域中的一个元素可以有多种解释n作用n提高语言灵活性n实现高层软件的复用多态n程序语言范畴n一名多用 n相同的语言结构可以代表不同类型的实体n类属 n相同的语言结构可以对不同类型的实体进行操作n面向对象程序设计具有一种独特的多态n一个公共的消息集可以发送到不同种类的对象,从而得到不同的处理多态n函数重载n在同一个作用域中,相同的标识符可以用于定义不同的函数,但要求这些函数应拥有不同的参数(参数类型或个数)n函数重载主要用于定义多个功能相同而参数不同的函数n在C+中,对重载函数的绑定采用静态绑定,由编译系统根据实参与形参的匹配实现操作符重载

2、n操作符重载n动机n语言提供的操作符只定义了针对基本数据类型操作的语义n操作符重载机制提供了对自定义数据类型进行操作的语义描述手段n作用n提高程序的可读性n提高语言的灵活性、可扩充性操作符重载class Complex double real,imag;public:Complex()real=0;imag=0;Complex(double r,double i)real=r;imag=i;Complex add(Complex&x);Complex a(1,2),b(3,4),c;c=a.add(b);class Complex double real,imag;public:Complex

3、()real=0;imag=0;Complex(double r,double i)real=r;imag=i;Complex operator+(Complex&x)Complex temp;temp.real=real+x.real;temp.imag=imag+x.imag;return temp;Complex a(1,2),b(3,4),c;c=a.operator+(b);c=a+b易理解优先级结合性操作符重载class Complex double real,imag;public:Complex()real=0;imag=0;Complex(double r,double i)

4、real=r;imag=i;friend Complex operator+(Complex&c1,Complex&c2);Complex operator+(Complex&c1,Complex&c2)Complex temp;temp.real=c1.real+c2.real;temp.imag=c1.imag+c2.imag;return temp;Complex a(1,2),b(3,4),c;c=a+b;operator+(a,b)至少包含一个用户自定义类型至少包含一个用户自定义类型(new、delete除外)除外)示例enum Day SUN,MON,TUE,WED,THU,FRI

5、,SAT;void main()Day d=SAT;+d;cout d;Day&operator+(Day&d)return d=(d=SAT)?SUN:Day(d+1);ostream&operator (ostream&o,Day&d)switch(d)case SUN:o SUN endl;break;case MON:o MON endl;break;case TUE:o TUE endl;break;case WED:o WED endl;break;case THU:o THU endl;break;case FRI:o FRI endl;break;case SAT:o SAT

6、endl;break;return o;操作符重载n可重载的操作符n.*:?:n操作符重载基本原则n方式n类成员函数n带有类参数的全局函数n遵循已有操作符的语法n单目/双目n优先级n结合性n遵循已有操作符的语义n除操作符=外,重载的操作符可以继承class A int x;public:A(int i):x(i)void f()void g();void(A:*p_f)();p_f=A:f;(a.*p_f)();操作符重载n双目操作符重载n类成员函数n格式 operator#()nthis 隐含n使用 a,b;a#b;a.operator#(b);操作符重载n全局函数n友元 friend op

7、erator#(,)n格式 operator#(,)n限制 =()不能作为全局函数重载操作符重载n区别n成员函数只需给一个参数,而全局函数必须给两个参数n有时必须用全局函数重载操作符class CL int count;public:friend CL operator+(int i,CL&a);friend CL operator+(CL&a,int i);;obj+1010+obj?=()不能作为全局函数重载?操作符重载n永远不要重载&和|char*p;if(p!=0)&(strlen(p)10)if (expressin1&expression2)if (expression1.oper

8、ator&(expression2)if (operator&(expression1,expression2)操作符重载class Rational public:Rational(int,int);private:int n,d;const Rational&operator*(const Rational&r);nreturn Rational(n*r.n,d*r.d);nRational*result =new Rational(n*r.n,d*r.d);return*result;nstatic Rational result;result.n=n*r.n;result.d=d*r.

9、d;return result;w=x*y*zif(a*b)=(c*d)尽可能让事情有效率,但不是过度有效率多态n单目操作符重载n类成员函数nthis 隐含n格式 operator#()n全局函数 operator#()多态na+vs+an+左值class Counter int value;public:Counter()value=0;Counter&operator+()/+a value+;return*this;Counter operator+(int)/a+Counter temp=*this;value+;return temp;dummy argumentprefix ope

10、ratorpostfix operator特殊操作符重载n=n默认赋值操作符重载函数n逐个成员赋值(member-wise assignment)n对含有对象成员的类,该定义是递归的n自定义赋值操作符重载函数n资源n赋值操作符重载不能继承赋值操作符重载不能继承特殊操作符重载 class A int x,y;char*p;public:A&operator=(A&a);A a,b;a=b;idle pointerx=a.x;y=a.y;delete p;p=new charstrlen(a.p)+1;strcpy(p,a.p);return*this;特殊操作符重载n避免自我赋值nSample:

11、class stringns=s?nclass A void f(A&a);nvoid f(A&a1,A&a2);nint f2(Derived&rd,Base&rb);nObject identitynContentnSame memory locationnObject identifierclass A public:ObjectID identity()const;.;A*p1,*p2;.p1-identity()=p2-identity()特殊操作符重载n class string char*p;public:string(char*p1)p=new char strlen(p1)+

12、1;strcpy(p,p1);char&operator(int i)return pi;virtual string()delete p;string s(“aacd”);s2=b;const char operator (int i)const return pi;const string cs(“const”);cs0=D;?特殊操作符重载n多维数组nclass Array2Dndata(2,3);ndata12;?class Array2D public:class Array1D public:Array1D(int*p)this-p=p;int&operator (int inde

13、x)return pindex;const int operator (int index)const return pindex;private:int*p;Array2D(int n1,int n2)p=new intn1*n2;num1=n1;num2=n2;virtual Array2D()delete p;Array1D operator (int index)return p+index*num2;const Array1D operator (int index)const return p+index*num2;private:int*p;int num1,num2;proxy

14、 classSurrogate 多维int*特殊操作符重载n smart pointersmart pointern为二元运算符class CPen int m_color;int m_width;public:void setColor(int c)m_color=c;int getWidth()return m_width;class CPanel CPen m_pen;int m_bkColor;public:CPen*operator-()return&m_pen;void setBkColor(int c)m_bkColor=c;;CPanel c;c-setColor(16);/c

15、.operator-()-setColor(16);/c.m_pen.setColor(16)c-getWidth();/c.operator-()-getWidth();/c.m_pen.getWidth()CPanel*p=&c;p-setBkColor(10);A a;a-f();a.operator-(?)重载重载时时按按一元操作符一元操作符重载重载描述描述 a.operator a.operator-()-f()()-f()Prevent memory Leak特殊操作符重载n()()class Func double para;int lowerBound,upperBound;p

16、ublic:double operator()(double,int,int);Func f;/计算对象f(2.4,0,8);特殊操作符重载n类型转换运算符n基本数据类型n自定义类class Rational public:Rational(int n1,int n2)n=n1;d=n2;operator double()return (double)n/d;private:int n,d;Rational r(1,2);double x=r;ostream f(“abc.txt”);if(f).重载 数值型:如 int特殊操作符重载nnew、deleten频繁调用系统的存储管理,影响效率n程

17、序自身管理内存,提高效率n方法n调用系统存储分配,申请一块较大的内存n针对该内存,自己管理存储分配、去配n通过重载 new 与 delete 来实现n重载的 new 和 delete 是静态成员n重载的 new 和 delete 遵循类的访问控制,可继承特殊操作符重载n重载 newnvoid*operator new(size_t size,)n名:operator newn返回类型:void*n第一个参数:size_t(unsigned int)n系统自动计算对象的大小,并传值给sizen其它参数:可有可无nA*p=new()A,表示传给new的其它实参nnew 的重载可以有多个n如果重载了

18、new,那么通过new 动态创建该类的对象时将不再调用内置的(预定义的)new特殊操作符重载n重载 deletenvoid operator delete(void*p,size_t size)n名:operator deleten返回类型:voidn第一个参数:void*n被撤销对象的地址n第二个参数:可有可无;如果有,则必须是size_t 类型n被撤消对象的大小ndelete 的重载只能有一个n如果重载了delete,那么通过delete 撤消对象时将不再调用内置的(预定义的)delete模板templaten模板n源代码复用机制n参数化模块n对程序模块(如:类、函数)加上类型参数类型参数

19、n对不同类型的数据实施相同的操作n多态的一种形式nC+n类属函数n类属类模板template functionn类属函数template functionn同一函数对不同类型的数据完成相同的操作n宏实现n#define max(a,b)(a)(b)?(a):(b)n缺陷n只能实现简单的功能n没有类型检查n重复计算模板n函数重载int max(int,int);double max(double,double);A max(A,A);n缺陷n需要定义的重载函数太多n定义不全模板n函数指针 void sort(void*,unsigned int,unsigned int,int (*cmp)(v

20、oid*,void*)n缺陷n需要定义额外参数n大量指针运算n实现起来复杂n可读性差template 引入的目标:完全完全清晰清晰模板n函数模板void sort(int A,unsigned int num)for(int i=1;inum;i+)for(int j=0;j Aj+1)int t=Aj;Aj=Aj+1;Aj+1=t;TTtemplate int a100;sort(a,100);double b200;sort(b,200);class C C a300;sort(a,300);必须重载必须重载操作符操作符 =copy constructor模板n函数模板定义了一类重载的函数

21、n编译系统自动实例化函数模板n函数模板的参数n可有多个类型参数,用逗号分隔n可带普通参数n必须列在类型参数之后n调用时需显式实例化template void f(T1 a,T2 b).template void f(T a)T tempsize;.f(1);模板n函数模板与函数重载配合使用template T max(T a,T b)return ab?a:b;int x,y,z;double l,m,n;z=max(x,y);l=max(m,n);问题:max(x,m)如何处理?定义一个max的重载函数:double max(int a,double b)return ab?a:b;模板te

22、mplate classn类属类类定义带有类型参数template class Stack T buffer100;public:void push(T x);T pop();template void Stack:push(T x)template T Stack:pop()Stack st1;Stack st2;class Stack int buffer100;public:void push(int x);int pop();void Stack:push(int x)int Stack:pop()Stack st1;显式实例化模板n定义了若干个类n显式实例化n可带有多个参数n可带有普

23、通参数n逗号分隔n须放在类型参数之后n类模板中的静态成员属于实例化后的类n不同实例之间不存在共享静态成员?静态成员?模板例template class Stack T buffersize;public:void push(T x);T pop();template void Stack:push(T x)template T Stack:pop()Stack st1;Stack st2;模板n模板是一种代码复用机制n源代码复用n实例化:生成具体的函数/类n函数模板的实例化n隐式实现n根据具体模板函数调用n类模板的实例化n创建对象时显式指定n是是否否实实例例化化模模板板的的某某个个实实例例由由

24、使使用用点点来来决决定定;如如果果未未使使用用到到一个模板的某个实例,则编译系统不会生成相应实例的代码一个模板的某个实例,则编译系统不会生成相应实例的代码模板nC+中模块是分别编译n如果在模块A中要使用模块B中定义的某模板的实例,而在模块B中未使用这个实例,则模块A无法使用这个实例#include file1.htemplate void S:f()template T max(T x,T y)return xy?x:y;void main()int a,b;max(a,b);S x;x.f();template class S T a;public:void f();#include fil

25、e1.hextern double max(double,double);void sub()max(1.1,2.2);/Error S x;x.f();/Errorfile1.cppfile1.hfile2.cppC+中模板的完整定义通常出现在头文件中中模板的完整定义通常出现在头文件中Template MetaProgrammingtemplateclass Fib public:enum value=Fib:value+Fib:value;void main()cout Fib:value endl;template class Fib public:enum value=1;templa

26、te class Fib public:enum value=1;/calculated at compile time异常处理n错误n语法错误n程序书写不符合语法规则n编译系统n逻辑错误n程序设计不当造成程序没有完成预期的功能n测试n异常 Exceptionn运行环境造成n内存不足、文件操作失败等n异常处理异常处理n特征n可以预料n无法避免n作用n预见性处理n提高程序鲁棒性(Robustness)n问题n发现异常之处与处理异常之处不一致void f(char*str)ifstream file(str);if (file.fail()/异常处理 int x;file x;异常处理n常见处理方

27、法n函数参数n返回值n引用参数n逐层返回n缺陷n程序结构不清楚异常处理nC+异常处理机制n一种专门、清晰描述异常处理过程的机制n处理机制ntryn监控可能造成异常的操作(语句块)nthrown抛掷异常对象ncatchn捕获并处理try throw catch ()异常处理ncatchn类型:异常类型,匹配规则同函数重载n变量:存储异常对象,可省n一个try 语句块的后面可以跟多个catch 语句块,用于捕获不同类型的异常进行处理void f().throw 1;.throw 1.0;.throw abcd;.try f();catch(int)/处理throw 1;catch(double)/

28、throw 1.0 catch(char*)/throw abcd 异常处理n异常处理的嵌套fgh 调用关系h()throw 1;/由g捕获并处理 throw“abcd”;/由 f捕获并处理g()try h();catch(int)f()try g();catch(int)catch(char*)如果抛掷的异常对象在调用链上没有给出捕获,则调系统的abort作标准异常处理异常处理n定义异常类n对于派生层次结构的异常处理,要注意catch 块组中的顺序int f()try .throw WrongFormat catch(NonExist).catch(DiskSeekError)catch(F

29、ileErrors)class FileErrors ;class NonExist:public FileErrors ;class WrongFormat:public FileErrors ;class DiskSeekError:public FileErrors ;异常处理n特例n无参数thrown将捕获到的异常对象重新抛掷出去 catch(int)throw;ncatch()n默认异常处理nCatch exceptions by reference I/O 处理n基于函数库的I/On基于类库的I/Oiosistreamifstreamistrstreamostreamofstrea

30、mostrstreamiostreamfstreamstrstreamI/O 处理nI/O流库的三类输入/输出操作n控制台I/O标准I/O设备ncin、cout、cerr、clogn文件I/O n字符串I/OI/O 处理n操作符重载n对自定义类的对象的I/On全局(友元)函数重载class CPoint2D double x,y;public:friend ostream&operator (ostream&,CPoint2D&);ostream&operator (ostream&out,CPoint2D&a)out a.x ,a.y endl;return out;CPoint2D a;c

31、out a;class CPoint3D:public CPoint2D double z;.CPoint3D b;cout b;只显示b.x和b.y,而没显示b.zostream&operator (ostream&out,CPoint3D&b)out b.x ,b.y,b.z endl;return out;friend ostream&operator (ostream&,CPoint3D&);Virtualizing non-member functionsI/O 处理class CPoint2D double x,y;public:virtual void display(ostre

32、am&out)out x ,y endl;ostream&operator (ostream&out,CPoint2D&a)a.display(out);return out;class CPoint3D:public CPoint2D double z;public:void display(ostream&out)CPoint2D:display();out ,z endl;Virtualizing constructorsnVirtual constructornVirtual functionnConstructornQuestionn【报纸】n文字、图形TextBlockGraphi

33、cListObjectsNewsLetterNLComponentpointersVirtualizing constructorsclass NLComponent;class TextBlock:public NLComponent;class Graphic:public NLComponent;class NewsLetter public:NewsLetter(istream&str)while(str)components.push_back(readComponent(str);static NLComponent*readComponent(istream&str);priva

34、te:list components;NewsLetter(const NewsLetter&rhs)for(list:iterator it=ponent.begin();it!=ponent.end();+it)component.push_back(?);new TextBlock?Graphic?Virtualizing constructorsnvirtual NLComponent*clone()const=0;nvirtual TextBlock*clone()const return new TextBlock(*this);nvirtual Graphic *clone()c

35、onst return new Graphic(*this);nNewsLetter:NewsLetter(const NewsLetter&rhs)for(list:iterator it=ponent.begin();it!=ponent.end();+it)component.push_back(*it)-clone();Know what functions C+silently writes and callsnclass Empty ;nclass Empty Empty();Empty(const Empty&);Empty();Empty&operator=(const Emp

36、ty&);Empty*operator&();const Empty*operator&()const;Never treat arrays polymorphicallynQuestionclass BST ;class BalencedBST:public BST ;void printBSTArray(ostream&s,const BST array,int numElements)for(int i=0;i numElements;i+)s processAdoption();catch()delete pa;throw;delete pa;结构破碎被迫重复“清理码”集中处理?Use

37、 destructors to prevent resource leaksnSolutionnSmart pointersnTemplate class auto_ptr public:auto_ptr(T*p=0):ptr(p)auto_ptr()delete ptr;T*operator-()const return ptr;T&operator*()const return*ptr;private:T*ptr;Use destructors to prevent resource leaks void processAdoptions(istream&dataSource)while(

38、dataSource)auto_ptr pa(readALA(dataSource);pa-processAdoption();n【GUI应用软件中的某个显示信息的函数】nvoid displayInfo(const Information&info)WINDOW_HANDLE w(createWindow();display info in window corresponding to w;destroyWindows(w);Use destructors to prevent resource leaksclass WindowHandle public:WindowHandle(WIN

39、DOW_HANDLE handler):w(handler)WindowHandle()destroyWindow(w);operator WINDOW_HANDLE()return w;private:WINDOW_HANDLE w;WindowHandle(const WindowHandle&);WindowHandle&operator=(const WindowHandle&);void displayInfo(const Information&info)WindowHandle w(createWindow()display info in window corresponding to w;

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com