c程序设计(part 3)_第1页
c程序设计(part 3)_第2页
c程序设计(part 3)_第3页
c程序设计(part 3)_第4页
c程序设计(part 3)_第5页
已阅读5页,还剩59页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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)

3、;class Complex double real, imag; public:Complex() 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易理解优先级结合性整理课件操作符重载cl

4、ass Complex double real, imag; public:Complex() real = 0; imag = 0; Complex(double r, double i) 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 te

5、mp; Complex a(1,2),b(3,4),c; c = a + b;operator + (a, b)至少包含一个用户自定义类型至少包含一个用户自定义类型(new、delete除外)除外)整理课件示例enum Day SUN, MON, TUE, WED, THU, FRI, 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 S

6、UN 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 endl;break;return o;整理课件操作符重载n可重载的操作符n. .* : ?: n操作符重载基本原则n方式n类成员函数n带有类参数的全局函数n遵循已有操作符的语法n单目/双目n优先级n结合性n遵循已有操作符的语义n除操作符=外,重载的操作符可以继承cla

7、ss 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 operator # (,)n格式 operator # (,) n限制 = () 不能作为全局函数重载整理课件操作符重载n区别n成员函数只需给一个参数,而全局函数必须给两个参数n有时必须用全局函数

8、重载操作符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.operator&(expression2)if (operator &(expression1, expre

9、ssion2)整理课件操作符重载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.d; return result;w = x*y*zif

10、 (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 argumen

11、tprefix operatorpostfix 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

12、,a.p); return *this;整理课件特殊操作符重载n避免自我赋值nSample: 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()整理课件特殊操作

13、符重载nclass string char *p; public:string(char *p1) p = new char strlen(p1)+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);n

14、data12; ?整理课件class Array2D public:class Array1D public:Array1D(int *p) this-p = p; int& operator (int index) 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

15、 (int index) return p+index*num2; const Array1D operator (int index) const return p+index*num2; private:int *p;int num1, num2;proxy 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

16、 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.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

17、;a-f();a.operator-( ?)重载重载时时按按一元操作符一元操作符重载重载描述描述 a.operator a.operator -()-f()()-f()Prevent memory Leak整理课件特殊操作符重载n( )( ) class Func double para;int lowerBound, upperBound; public:double operator () (double, int, int);Func f;/计算对象f(2.4, 0, 8);整理课件特殊操作符重载n类型转换运算符n基本数据类型n自定义类class Rational public :Rat

18、ional(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程序自身管理内存,提高效率n方法n调用系统存储分配,申请一块较大的内存n针对该内存,自己管理存储分配、去配n通过重载 new 与 delete 来实现n重载的 new 和 delete 是

19、静态成员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如果重载了new,那么通过new 动态创建该类的对象时将不再调用内置的(预定义的)new整理课件特殊操作符重载n重载 deletenvoid operator

20、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对程序模块(如:类、函数)加上类型参数类型参数n对不同类型的数据实施相同的操作n多态的一种形式nC+n类属函数n类属类整理课件模板template functionn类属函数

21、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) (void *, void *) )n缺陷n需要定义额外参数n大量指针运算n实现起来复杂n可读

22、性差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函数模板定义了一类重载的函数n编译系统自动实例化函数模板

23、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

24、? a : b; 整理课件模板template 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;显式实例

25、化整理课件模板n定义了若干个类n显式实例化n可带有多个参数n可带有普通参数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根据具体模板

26、函数调用n类模板的实例化n创建对象时显式指定n是否实例化模板的某个实例由使用点来决定是否实例化模板的某个实例由使用点来决定;如果未使用到如果未使用到一个模板的某个实例,则编译系统不会生成相应实例的代码一个模板的某个实例,则编译系统不会生成相应实例的代码整理课件模板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);

27、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(); /ErrorC+中模板的完整定义通常出现在头文件中中模板的完整定义通常出现在头文件中整理课件Template MetaProgrammingtemplateclass Fib public: enum value = Fib:value + Fib:value ;void main() cout Fib:valu

28、e endl; template class Fib public: enum value = 1 ;template 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(ch

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

30、的异常进行处理void f() . throw 1; . throw 1.0; . throw abcd; . try f(); catch ( int ) /处理throw 1; 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

31、定义异常类n对于派生层次结构的异常处理,要注意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 ;整理课件异常处理n特例n无参数thrown将捕获到的异常对象重新抛掷出去 catch

32、 (int) throw; ncatch() n默认异常处理nCatch exceptions by reference 整理课件I/O 处理n基于函数库的I/On基于类库的I/Oiosistreamifstreamistrstreamostreamofstreamostrstreamiostreamfstreamstrstream整理课件I/O 处理nI/O流库的三类输入/输出操作n控制台I/O标准I/O设备ncin、cout、cerr、clogn文件I/On字符串I/O整理课件I/O 处理n操作符重载n对自定义类的对象的I/On全局(友元)函数重载class CPoint2D double

33、 x, y; public: friend ostream& operator (ostream&, CPoint2D &);ostream& operator (ostream& out, CPoint2D& a) out a.x , a.y endl;return out; CPoint2D a;cout a;class CPoint3D: public CPoint2D double z; ;. CPoint3D b; cout b; 只显示和,而没显示ostream& operator (ostream& out, CPoint3D & b) out b.x , b.y , b.z e

34、ndl;return out; friend ostream& operator (ostream &, CPoint3D &);Virtualizing non-member functions整理课件I/O 处理class CPoint2D double x, y;public: virtual void display(ostream& out) out x , y endl; ;ostream& operator (ostream& out, CPoint2D &a) a.display(out); return out; class CPoint3D: public CPoint2D

35、 double z; public: void display(ostream& out) CPoint2D:display(); out , z endl; ;整理课件Virtualizing constructorsnVirtual constructornVirtual functionnConstructornQuestionn【报纸】n文字、图形TextBlockGraphicListObjectsNewsLetterNLComponentpointers整理课件Virtualizing constructorsclass NLComponent ;class TextBlock :

36、 public NLComponent ;class Graphic : public NLComponent ;class NewsLetter public: NewsLetter(istream& str) while (str) components.push_back(readComponent(str); static NLComponent * readComponent(istream& str); private: list components;NewsLetter(const NewsLetter& rhs) for (list:iterator it=ponent.be

37、gin();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() const 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 Empty&);Empty *operator &(

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论