c程序设计(part3).ppt

上传人:牧羊曲112 文档编号:6503574 上传时间:2023-11-07 格式:PPT 页数:64 大小:366.50KB
返回 下载 相关 举报
c程序设计(part3).ppt_第1页
第1页 / 共64页
c程序设计(part3).ppt_第2页
第2页 / 共64页
c程序设计(part3).ppt_第3页
第3页 / 共64页
c程序设计(part3).ppt_第4页
第4页 / 共64页
c程序设计(part3).ppt_第5页
第5页 / 共64页
点击查看更多>>
资源描述

《c程序设计(part3).ppt》由会员分享,可在线阅读,更多相关《c程序设计(part3).ppt(64页珍藏版)》请在三一办公上搜索。

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

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

3、g=i;Complex operator+(Complex,c=a+b易理解优先级结合性,操作符重载,class Complex double real,imag;public:Complex()real=0;imag=0;Complex(double r,double i)real=r;imag=i;friend Complex operator+(Complex,operator+(a,b),至少包含一个用户自定义类型(new、delete除外),示例,enum Day SUN,MON,TUE,WED,THU,FRI,SAT;,void main()Day d=SAT;+d;cout d;

4、,Day,ostream,操作符重载,可重载的操作符.*:?:操作符重载基本原则方式类成员函数带有类参数的全局函数遵循已有操作符的语法单目/双目优先级结合性遵循已有操作符的语义除操作符=外,重载的操作符可以继承,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)();,操作符重载,双目操作符重载类成员函数格式 operator#()this 隐含使用 a,b;a#b;a.operator#(b);,操作符重载,全局函数友元 friend operator#(,)格式 operato

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

6、s Rational public:Rational(int,int);private:int n,d;const Rational,w=x*y*z,if(a*b)=(c*d),尽可能让事情有效率,但不是过度有效率,多态,单目操作符重载类成员函数this 隐含格式 operator#()全局函数 operator#(),多态,a+vs+a+左值,class Counter int value;public:Counter()value=0;Counter,dummy argument,prefix operator,postfix operator,特殊操作符重载,=默认赋值操作符重载函数逐个

7、成员赋值(member-wise assignment)对含有对象成员的类,该定义是递归的自定义赋值操作符重载函数资源赋值操作符重载不能继承,特殊操作符重载,class A int x,y;char*p;public:A,A a,b;a=b;idle pointer,x=a.x;y=a.y;delete p;p=new charstrlen(a.p)+1;strcpy(p,a.p);return*this;,特殊操作符重载,避免自我赋值Sample:class strings=s?class A void f(AObject identityContentSame memory locatio

8、nObject identifier,class A public:ObjectID identity()const;.;A*p1,*p2;.p1-identity()=p2-identity(),特殊操作符重载,class string char*p;public:string(char*p1)p=new char strlen(p1)+1;strcpy(p,p1);char,const char operator(int i)const return pi;,const string cs(“const”);cs0=D;?,特殊操作符重载,多维数组class Array2Ddata(2,3

9、);data12;?,class Array2D public:class Array1D public:Array1D(int*p)this-p=p;int,proxy classSurrogate 多维,int*,特殊操作符重载,smart pointer为二元运算符,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-()r

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

11、operator()(double,int,int);Func f;/计算对象f(2.4,0,8);,特殊操作符重载,类型转换运算符基本数据类型自定义类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,特殊操作符重载,new、delete频繁调用系统的存储管理,影响效率程序自身管理内存,提高效率方法

12、调用系统存储分配,申请一块较大的内存针对该内存,自己管理存储分配、去配通过重载 new 与 delete 来实现重载的 new 和 delete 是静态成员重载的 new 和 delete 遵循类的访问控制,可继承,特殊操作符重载,重载 newvoid*operator new(size_t size,)名:operator new返回类型:void*第一个参数:size_t(unsigned int)系统自动计算对象的大小,并传值给size其它参数:可有可无A*p=new()A,表示传给new的其它实参new 的重载可以有多个如果重载了new,那么通过new 动态创建该类的对象时将不再调用内

13、置的(预定义的)new,特殊操作符重载,重载 deletevoid operator delete(void*p,size_t size)名:operator delete返回类型:void第一个参数:void*被撤销对象的地址第二个参数:可有可无;如果有,则必须是size_t 类型被撤消对象的大小delete 的重载只能有一个如果重载了delete,那么通过delete 撤消对象时将不再调用内置的(预定义的)delete,模板template,模板源代码复用机制参数化模块对程序模块(如:类、函数)加上类型参数对不同类型的数据实施相同的操作多态的一种形式C+类属函数类属类,模板template

14、 function,类属函数template function同一函数对不同类型的数据完成相同的操作宏实现#define max(a,b)(a)(b)?(a):(b)缺陷只能实现简单的功能没有类型检查重复计算,模板,函数重载int max(int,int);double max(double,double);A max(A,A);缺陷需要定义的重载函数太多定义不全,模板,函数指针 void sort(void*,unsigned int,unsigned int,int(*cmp)(void*,void*)缺陷需要定义额外参数大量指针运算实现起来复杂可读性差,template 引入的目标:完全

15、清晰,模板,函数模板,void sort(int A,unsigned int num)for(int i=1;i Aj+1)int t=Aj;Aj=Aj+1;Aj+1=t;,T,T,template,int a100;sort(a,100);double b200;sort(b,200);,class C C a300;sort(a,300);,必须重载操作符=copy constructor,模板,函数模板定义了一类重载的函数编译系统自动实例化函数模板函数模板的参数可有多个类型参数,用逗号分隔可带普通参数必须列在类型参数之后调用时需显式实例化,template void f(T1 a,T2

16、 b).,template void f(T a)T tempsize;.f(1);,模板,函数模板与函数重载配合使用,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;,模板template class,类属类类定义带有类型参数,template class Stack T buffer100;public:void push(T x);T

17、 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;,显式实例化,模板,定义了若干个类显式实例化可带有多个参数可带有普通参数逗号分隔须放在类型参数之后,类模板中的静态成员属于实例化后的类不同实例之间不存在共享,静态成员?,模板例,template class Stack T bu

18、ffersize;public:void push(T x);T pop();template void Stack:push(T x)template T Stack:pop()Stack st1;Stack st2;,模板,模板是一种代码复用机制源代码复用实例化:生成具体的函数/类函数模板的实例化隐式实现根据具体模板函数调用类模板的实例化创建对象时显式指定是否实例化模板的某个实例由使用点来决定;如果未使用到一个模板的某个实例,则编译系统不会生成相应实例的代码,模板,C+中模块是分别编译如果在模块A中要使用模块B中定义的某模板的实例,而在模块B中未使用这个实例,则模块A无法使用这个实例,#i

19、nclude 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 file1.hextern double max(double,double);void sub()max(1.1,2.2);/Error S x;x.f();/Error,file1.cpp,file1.h,file2.cpp,C+中模板的完整定义通常出现在头文件中,Template

20、MetaProgramming,templateclass Fib public:enum value=Fib:value+Fib:value;void main()cout:value endl;,template class Fib public:enum value=1;template class Fib public:enum value=1;,/calculated at compile time,异常处理,错误语法错误程序书写不符合语法规则编译系统逻辑错误程序设计不当造成程序没有完成预期的功能测试异常 Exception运行环境造成内存不足、文件操作失败等异常处理,异常处理,特征

21、可以预料无法避免作用预见性处理提高程序鲁棒性(Robustness)问题发现异常之处与处理异常之处不一致,void f(char*str)ifstream file(str);if(file.fail()/异常处理 int x;file x;,异常处理,常见处理方法函数参数返回值引用参数逐层返回缺陷程序结构不清楚,异常处理,C+异常处理机制一种专门、清晰描述异常处理过程的机制处理机制try监控可能造成异常的操作(语句块)throw抛掷异常对象catch捕获并处理,try,throw,catch(),异常处理,catch类型:异常类型,匹配规则同函数重载变量:存储异常对象,可省一个try 语句块

22、的后面可以跟多个catch 语句块,用于捕获不同类型的异常进行处理,void f().throw 1;.throw 1.0;.throw abcd;.,try f();catch(int)/处理throw 1;catch(double)/throw 1.0 catch(char*)/throw abcd,异常处理,异常处理的嵌套fgh 调用关系,h()throw 1;/由g捕获并处理 throw“abcd”;/由 f捕获并处理,g()try h();catch(int),f()try g();catch(int)catch(char*),如果抛掷的异常对象在调用链上没有给出捕获,则调系统的ab

23、ort作标准异常处理,异常处理,定义异常类对于派生层次结构的异常处理,要注意catch 块组中的顺序,int f()try.throw WrongFormat catch(NonExist).catch(DiskSeekError)catch(FileErrors),class FileErrors;class NonExist:public FileErrors;class WrongFormat:public FileErrors;class DiskSeekError:public FileErrors;,异常处理,特例无参数throw将捕获到的异常对象重新抛掷出去 catch(int)

24、throw;catch()默认异常处理Catch exceptions by reference,I/O 处理,基于函数库的I/O基于类库的I/O,ios,istream,ifstream,istrstream,ostream,ofstream,ostrstream,iostream,fstream,strstream,I/O 处理,I/O流库的三类输入/输出操作控制台I/O标准I/O设备cin、cout、cerr、clog文件I/O字符串I/O,I/O 处理,操作符重载对自定义类的对象的I/O全局(友元)函数重载,class CPoint2D double x,y;public:friend

25、 ostream,class CPoint3D:public CPoint2D double z;.CPoint3D b;cout b;,只显示b.x和b.y,而没显示b.z,ostream,friend ostream,Virtualizing non-member functions,I/O 处理,class CPoint2D double x,y;public:virtual void display(ostream,Virtualizing constructors,Virtual constructorVirtual functionConstructorQuestion【报纸】文字

26、、图形,TextBlock,Graphic,ListObjects,NewsLetter,NLComponent,pointers,Virtualizing constructors,class NLComponent;class TextBlock:public NLComponent;class Graphic:public NLComponent;class NewsLetter public:NewsLetter(istream,NewsLetter(const NewsLetter,new TextBlock?Graphic?,Virtualizing constructors,vi

27、rtual NLComponent*clone()const=0;virtual TextBlock*clone()const return new TextBlock(*this);virtual Graphic*clone()const return new Graphic(*this);NewsLetter:NewsLetter(const NewsLetter,Know what functions C+silently writes and calls,class Empty;class Empty Empty();Empty(const Empty,Never treat arra

28、ys polymorphically,Questionclass BST;class BalencedBST:public BST;void printBSTArray(ostream,Use destructors to prevent resource leaks,Question-resource leaks【小动物收养保护中心】收养中心每天产生一个文件,包含当天的收养个案信息读取这个文件,为每个个案做适当的处理,Use destructors to prevent resource leaks,ALA,Puppy,Kitten,Adorable Little Animal(Abstra

29、ct Base Class),class ALA public:virtual void processAdoption()=0;.;,class Puppy:public ALA public:virtual void processAdoption();.;,class Kitten:public ALA public:virtual void processAdoption();.;,Use destructors to prevent resource leaks,void processAdoptions(istream,结构破碎被迫重复“清理码”集中处理?,Use destruct

30、ors to prevent resource leaks,SolutionSmart pointersTemplate class auto_ptr public:auto_ptr(T*p=0):ptr(p)auto_ptr()delete ptr;T*operator-()const return ptr;T,Use destructors to prevent resource leaks,void processAdoptions(istream,Use destructors to prevent resource leaks,class WindowHandle public:WindowHandle(WINDOW_HANDLE handler):w(handler)WindowHandle()destroyWindow(w);operator WINDOW_HANDLE()return w;private:WINDOW_HANDLE w;WindowHandle(const WindowHandle,void displayInfo(const Information,

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

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号