C++程序设计教学课件:CHAPTER 9 POLYMORPHISM

上传人:cl****1 文档编号:570087641 上传时间:2024-08-01 格式:PPT 页数:97 大小:319KB
返回 下载 相关 举报
C++程序设计教学课件:CHAPTER 9 POLYMORPHISM_第1页
第1页 / 共97页
C++程序设计教学课件:CHAPTER 9 POLYMORPHISM_第2页
第2页 / 共97页
C++程序设计教学课件:CHAPTER 9 POLYMORPHISM_第3页
第3页 / 共97页
C++程序设计教学课件:CHAPTER 9 POLYMORPHISM_第4页
第4页 / 共97页
C++程序设计教学课件:CHAPTER 9 POLYMORPHISM_第5页
第5页 / 共97页
点击查看更多>>
资源描述

《C++程序设计教学课件:CHAPTER 9 POLYMORPHISM》由会员分享,可在线阅读,更多相关《C++程序设计教学课件:CHAPTER 9 POLYMORPHISM(97页珍藏版)》请在金锄头文库上搜索。

1、C+ Programming CHAPTER 9 POLYMORPHISM1l9.1 Run-Time Versus Compile-Time Binding in C+l9.2 Name Overloading, Name Overriding, and Name Hidingl9.3 Abstract Base Classl9.4 Operator Overloading2PolymorphismPolymorphism is an essential feature of an object-oriented programming language. In technical term

2、s, polymorphism is the run-rime binding of a functions name to the code that implements the function.39.1 Run-Time Versus Compile-Time Binding in C+Compile-Time BindingCompile-time binding means the compiler determines what code is to be executed whenever the function is invoked. Including:A) Functi

3、on OverloadingB) Operator Overloading49.1 Run-Time Versus Compile-Time Binding in C+A functions name is associated with an entry point, the starting address of the code that implements the function.59.1 Run-Time Versus Compile-Time Binding in C+Example:#include using namespace std;void sayHi();int m

4、ain()sayHi();return 0;void sayHi()cout”Hello, cruel worlds!”endl;69.1 Run-Time Versus Compile-Time Binding in C+Example: Macro#define ADD(A,B) (A)+(B)79.1 Run-Time Versus Compile-Time Binding in C+Run-Time BindingRun-time binding is the binding of a functions name to an entry point when the program

5、is running, not when the program is being compiled.89.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismRequirements for C+ PolymorphismExample:#includeusing namespace std;class Point public:Point(double i, double j) x=i; y=j;double Area() const return 0.0;private:double x,

6、 y;99.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Polymorphismclass Rectangle:public Point public:Rectangle(double i, double j, double k, double l);double Area() const return w*h;private:double w,h;Rectangle:Rectangle(double i, double j, double k, double l) :Point(i,j) w=k; h=l;

7、109.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Polymorphismvoid fun(Point &s) coutArea=s.Area()endl; void main()Rectangle rec(3.0, 5.2, 15.0, 25.0);fun(rec);Output:Area=0 Question: Why the output is not 15*25?119.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Po

8、lymorphismRequirements:A) There must be an inheritance hierarchy.B) The classes in the hierarchy must have a virtual method with the same signature (virtual is a keyword).C) There must be either a pointer or a reference to a base class. The pointer or reference is used to invoke a virtual method.129

9、.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismExample:#includeusing namespace std;class Point public: Point(double i, double j) x=i; y=j; virtual double Area() const return 0.0; private:double x, y;139.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Pol

10、ymorphismclass Rectangle:public Point public: Rectangle(double i, double j, double k, double l); virtual double Area() const return w*h; private:double w,h;149.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Polymorphismvoid fun(Point &s) coutArea=s.Area()endl; void main()Rectangle r

11、ec(3.0, 5.2, 15.0, 25.0);fun(rec);/PolymorphismOutput:Area=375Rectangle: double Area()159.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismExample:#include using namespace std;class B0/base class B0public:virtual void display() /virtual method coutB0:display()endl; ;169.1

12、Run-Time Versus Compile-Time Binding in C+Requirements for C+ Polymorphismclass B1: public B0 /public inheritance public:void display() coutB1:display()endl; ;class D1: public B1 public: void display() coutD1:display()display(); void main()B0 b0, *p;/object and pointer of base classB1 b1;/object of

13、derived classD1 d1;/ object of derived classp=&b0;fun(p);/method of B0 is invokedp=&b1;fun(p);/ method of B1 is invokedp=&d1;fun(p);/ method of D1 is invokedOutput:B0:display()B1:display()D1:display()can be pointed to any object of derived classes189.1 Run-Time Versus Compile-Time Binding in C+Requi

14、rements for C+ PolymorphismRemarks:A) The virtual method must not be static method.B)The keyword virtual is used in declaring the methods, not in implementing the methods. 199.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismC) The virtual methods will be inherited from a

15、base class no matter the derived class declared them.Example:class TradesPersonpublic:virtural void sayHi()cout”Just hi.”endl;class Tinker:public TradesPerson ;int main()Tinker t1;t1.sayHi();/inherited from TradesPerson209.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismD

16、) The derived classes should be public inherited from the base class.219.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ PolymorphismExample:#include class Figureprotected: float x,y;public: void Set(float i, float j=0) x=i; y=j; virtual void ShowArea() ;class Triangle:public Figurep

17、ublic: void ShowArea() coutTriangle with height “ x“ and base; couty“ has an area of x*0.5*yn; ;229.1 Run-Time Versus Compile-Time Binding in C+Requirements for C+ Polymorphismclass Square: public Figurepublic: void ShowArea() coutSquare with dimension x*y; cout“ has an area of “ x*yn; ;class Circle

18、: public Figurepublic: void ShowArea() coutCircle with radius x; cout“ has an area of “ 3.14*x*xSet(12.0,8.0); p1=&s; p1-Set(12.0,8.0); p2=&c; p2-Set(10.0); for(int i=0;iShowArea();Output:249.1 Run-Time Versus Compile-Time Binding in C+Run-Time Binding and the VtableRun-Time Binding and the VtableC+

19、 uses a vtable (virtual table) to implement the run-time binding of virtual methods.259.1 Run-Time Versus Compile-Time Binding in C+Run-Time Binding and the VtableExample:class Bpublic:virtual void m1()/virtual methodvirtual void m2()/virtual method;class D: public Bpublic:virtual void m1()/override

20、 m1;269.1 Run-Time Versus Compile-Time Binding in C+Run-Time Binding and the VtableVirtual MethodSample Entry PointB:m1 0x7723B:m2 0x23b4D:m1 0x99a7D:m2 0x23b4279.1 Run-Time Versus Compile-Time Binding in C+Constructors and the DestructorConstructors and the DestructorA constructor cannot be virtual

21、. A destructor can be virtual.289.1 Run-Time Versus Compile-Time Binding in C+Constructors and the DestructorExample:class Cpublic:virtual C(); virtual C(int); virtual C(); virtual void m();Question:There are two errors in the code segment, why?/error/error/ok/ok299.1 Run-Time Versus Compile-Time Bi

22、nding in C+Constructors and the Destructorvirtual DestructorsExample:#include class B0public:B0()coutB0 destructor!n;/compile-time binding;309.1 Run-Time Versus Compile-Time Binding in C+Constructors and the Destructorclass B1: public B0public:B1()i_pointer = new int(0);B1()coutB1 destructor!n; dele

23、te i_pointer;private:int* i_pointer;319.1 Run-Time Versus Compile-Time Binding in C+Constructors and the Destructorvoid fun(B0 * b)delete b;void main()B0 * b0 = new B1;fun(b0);Output:B0 destructor!compile-time bindingQuestion: Why B1 was not destructed?329.1 Run-Time Versus Compile-Time Binding in C

24、+Constructors and the DestructorVirtual destructor is necessary if you try to delete an derived object by a pointer pointing to base class, or the destructor of derived class is invoked by a pointer of base class.339.1 Run-Time Versus Compile-Time Binding in C+Constructors and the DestructorExample:

25、#include class B0public:virtual B0()coutB0 destructor!n; /virtual destructor, can be invoked by /the object of derived class;349.1 Run-Time Versus Compile-Time Binding in C+Constructors and the Destructorclass B1: public B0public:B1()i_pointer = new int(0);B1()coutB1 destructor!n; delete i_pointer;p

26、rivate:int* i_pointer;359.1 Run-Time Versus Compile-Time Binding in C+Constructors and the Destructorvoid fun(B0 * b)delete b;void main()B0 * b0 = new B1;fun(b0);Output:B1 destructor!B0 destructor!369.2 Name Overloading, Name Overriding, and Name HidingName OverloadingTop-level functions can share a

27、 name if they have different signatures. Methods in the same class can share a name if they have different signatures, this is knows as name overloading. Name overloading always involves complie-time binding.379.2 Name Overloading, Name Overriding, and Name HidingName OverloadingExample:class Cpubli

28、c:C() C( int x );void f( double d)void f( char c)int main() C c1 ; / C( ) called C c2 ( 26 ) ;/ C( int x ) called f ( 3.14) ; / f ( double ) called f ( z) ; / f ( char ) called389.2 Name Overloading, Name Overriding, and Name HidingName OverridingName OverridingSuppose that base class B has a method

29、 m and its derived class D also has a method m with the same signature:A) If the methods are virtual, run-time binding is at work in any invocation of m through pointers or references. 399.2 Name Overloading, Name Overriding, and Name HidingName OverridingB) If the methods are virtual, the derived c

30、lass method D:m overrides the base class method B:m. C) If the methods are not virtual, compile-time binding is at work in any time.409.2 Name Overloading, Name Overriding, and Name HidingName OverridingExample:#include using namespace std;class Bpublic:void m( )cout”B:m”endl;class D: public Bpublic

31、:void m( )cout”D:m”m();return 0;Output:B:m429.2 Name Overloading, Name Overriding, and Name HidingName HidingSuppose that base class B has a nonvirtual method m and its derived class D also has a method m. Ds local method D:m is said to hide the inherited method B:m. Name hiding is particularly tric

32、ky if the derived classs method has a different signature than the base classs method of the same name.439.2 Name Overloading, Name Overriding, and Name HidingName HidingExample:#include using namespace std;class Bpublic:void m( int x )coutxendl;class D: public Bpublic:void m( )cout”Hi”Withdrawal(10

33、0.0);void main() Savings s(111,1000); Checking c(222,10000); func(&s); func(&c);56Exercise1:class two_point public:two_point();two_point(int, int );virtual two_point();void setX(int newx);void setY(int newy);int getX();int getY();void display();private:int x, y; ;57two_point:two_point() x=0;y=0;two_

34、point:two_point(int newx, int newy) x=newx; y=newy; two_point:two_point() int two_point:getX() return x; int two_point:getY() return y; void two_point:setX(int newx) x=newx; void two_point:setY(int newy) y=newy; void two_point:display()coutThe point is ( getX(),getY() endl; 58class three_point : pub

35、lic two_point public:three_point() z=0; three_point(int newx, int newy, int newz) z=newz; void setZ(int newz) z=newz;int getZ() return z;virtual three_point() private:int z;59void main()two_point tp;tp.setX(10);tp.setY(-10);tp.display();three_point p3(3,4,5);p3.display();Output:The point is (10,-10)

36、The point is (0,0)Question: Constructor of three_point cant offer the arguments to its base class two_point, how to solve it?609.3 Abstract Base ClassUses of Abstract Base ClassesExercise2:three_point:three_point(int newx, int newy, int newz) :two_point(newx,newy) z=newz;void main()three_point p3(3,

37、4,5);p3.display();Output:The point is (3,4)Question:Cant output z, how to solve it?619.3 Abstract Base ClassUses of Abstract Base ClassesExercise3:void three_point:display()two_point:display(); cout getZ() endl;629.3 Abstract Base ClassUses of Abstract Base Classesvoid main()two_point tp;tp.setX(10)

38、;tp.setY(-10);tp.display();three_point p3(3,4,5);p3.display();Output:The point is (10, -10)The three point is(3,4,5)Question:How to implement it using polymorphism?639.3 Abstract Base ClassUses of Abstract Base ClassesAnswer:class two_point public:two_point();two_point(int, int );two_point(); virtua

39、l void display();private:int x, y;649.4 Operator OverloadingLike function overloading, operator overloading is kind of compile-time binding, it refers to multiple definitions of operators such as +, +, and .659.4 Operator OverloadingArithmetic operators such as + are overloaded in the C+ language. F

40、or example, the + operator may designate either integer addition or floating-point addition.int i=4+8;float f=4.0+8.0;669.4 Operator OverloadingConvenience of operator overloading extends from built-in types, such as int and float, to classes. Indeed, the operator overloading is kind of function ove

41、rloading.Syntax:type operator ope(parameters) .679.4 Operator OverloadingRemarks:A) Number of parameters = parameters before overloaded 1 (except postincrement and postdecrement).B) If an operator is overloaded as a friend function, the number of parameters will not change. Also, at least one parame

42、ter should be user defined data type.689.4 Operator OverloadingRules:A) All the operators in C+ can be overloaded, except: member selector ( . ),member object selector( .* ), scope resolution( : ), conditional( ?: ), and sizeof().B) Only operators exist in C+ can be overloaded.699.4 Operator Overloa

43、dingC) Operator overloading cant change the precedence and combinableness.D) Operator overloading cant change the sum of the parameters.E) At least one parameter should be user defined data type in operator overloading.F) An overloaded operator must be either a method, or a top-level function.709.4

44、Operator OverloadingBasic Operator OverloadingIf two-operand operator B is overloaded, the code segmentoprd1 B oprd2 means oprd1.operator B(oprd2 ).Just like a method.719.4 Operator OverloadingBasic Operator OverloadingIf one-operand preoperator B is overloaded, the code segmentB oprdmeansoprd.opera

45、tor B().729.4 Operator OverloadingBasic Operator OverloadingIf one-operand postoperator B is overloaded, the code segmentB oprd meansoprd.operator B(0 )739.4 Operator OverloadingBasic Operator OverloadingExample:#includeusing namespace std;class complexpublic:complex(double r=0.0,double i=0.0)real=r

46、;imag=i; complex operator + (complex c2); /+ overloaded as methodcomplex operator - (complex c2); /- overloaded as methodvoid display();/output the complex numberprivate:double real; double imag;749.4 Operator OverloadingBasic Operator Overloadingcomplex complex:operator +(complex c2) complex c;c.re

47、al=c2.real+real;c.imag=c2.imag+imag;return complex(c.real,c.imag);759.4 Operator OverloadingBasic Operator Overloadingcomplex complex:operator -(complex c2) complex c;c.real=real-c2.real;c.imag=imag-c2.imag;return complex(c.real,c.imag);769.4 Operator OverloadingBasic Operator Overloadingvoid comple

48、x:display() cout(real,imag)endl; void main() complex c1(5,4),c2(2,10),c3; coutc1=; c1.display();coutc2=; c2.display();c3=c1-c2;coutc3=c1-c2=;c3.display();c3=c1+c2;coutc3=c1+c2=;c3.display();Output:c1=(5,4)c2=(2,10)c3=c1-c2=(3,-6)c3=c1+c2=(7,14)779.4 Operator OverloadingOperator Overloading Using Top

49、-Level FunctionsOperator Overloading Using Top-Level FunctionsAn operator that is overloaded as a top-level function must include a class object among its arguments.789.4 Operator OverloadingOperator Overloading Using Top-Level FunctionsExample:class complexpublic:complex(double r=0.0,double i=0.0)

50、real=r;imag=i; void display();/output the complex numberpublic: /private members in last exampledouble real; double imag;799.4 Operator OverloadingOperator Overloading Using Top-Level Functionscomplex operator+(const complex& c1, const complex& c2)return complex( (c1.real+c2.real), (c1.imag+c2.imag)

51、 );int main()Complex a, b( 4.3, -8.2 );a=b+54.3;a=54.3+b;a.display();return 0;Output:(58.6,-8.2)Question:How to access the private members in the class complex?809.4 Operator OverloadingOverloading the Increment and Decrement OperatorOverloading the Increment and Decrement OperatorThe declarationope

52、rator+( )with no parameters overloads the preincrement operator.The declarationoperator+( int )with a single int parameter overloads the postincrement operator.819.4 Operator OverloadingOverloading the Increment and Decrement OperatorRemark:The int parameter in the postincrement form serves to disti

53、nguish it from the preincrement form. The parameter itself need not be used.829.4 Operator OverloadingOverloading the Increment and Decrement OperatorExample: Clock#includeusing namespace std;class Clock public: Clock(int NewH=0, int NewM=0, int NewS=0); void ShowTime(); Clock& operator +(); /preinc

54、rement Clock operator +(int); /postincrement, parameter int is not usedprivate: int Hour,Minute,Second;839.4 Operator OverloadingOverloading the Increment and Decrement OperatorClock& Clock:operator +()Second+;if(Second=60) Second=Second-60; Minute+; if(Minute=60) Minute=Minute-60; Hour+; Hour=Hour%

55、24; return *this;Whats the difference?849.4 Operator OverloadingOverloading the Increment and Decrement OperatorClock Clock:operator +(int) Clock old=*this; +(*this); return old;/859.4 Operator OverloadingOverloading the Increment and Decrement Operatorvoid main()Clock myClock(23,59,59);coutFirst ti

56、me output:;myClock.ShowTime();coutShow myClock+:;(myClock+).ShowTime();coutShow +myClock:;(+myClock).ShowTime();Output:First time output: 23:59:59Show myClock+: 23:59:59Show +myClock: 0:0:1869.4 Operator OverloadingOverloading the Increment and Decrement OperatorQuestion:The preincrement returns a r

57、eference and the post increment returns an object, why?Answer:In the preincrement, the parameter and the return value are the same object.In the postincrement, the paramenter and the return value are different objects.879.4 Operator OverloadingOverloading the Increment and Decrement OperatorExercise

58、: Overload the operator ( ), so that a(i,j) equals to a.Aij.#include class Sample public: int A1010; int &operator()(int,int); ; int &Sample:operator()(int x,int y) return Axy; 889.4 Operator OverloadingOverloading the Increment and Decrement Operatorvoid main() Sample a; int i,j; for(i=0;i10;i+) fo

59、r(j=0;j10;j+) a.Aij=i+j; for(i=0;i10;i+) couta(i,1) ; coutendl; 899.4 Operator OverloadingFriend FunctionsFriend FunctionsA classs private members are accessible only to its methods and its friend functions. A classs protected members are accessible only to methods in its class hierarchy and its fri

60、end functions. Operators can be overloaded as friend methods, too.909.4 Operator OverloadingFriend FunctionsIf two-operand operator B is overloaded as a friend function, the code segmentoprd1 B oprd2 means operator B(oprd1,oprd2 ).919.4 Operator OverloadingFriend FunctionsIf one-operand preoperator

61、B is overloaded as a friend function, the code segmentB oprdmeansoperator B(oprd ).929.4 Operator OverloadingFriend FunctionsIf one-operand postoperator B is overloaded as a friend function, the code segmentB oprd meansoperator B(oprd,0 )939.4 Operator OverloadingFriend FunctionsExample:#includeusin

62、g namespace std;class complexpublic:complex(double r=0.0,double i=0.0) real=r; imag=i; / + overloaded as friend functionfriend complex operator + (complex c1,complex c2);/ - overloaded as friend functionfriend complex operator - (complex c1,complex c2);void display();private:double real;double imag;

63、949.4 Operator OverloadingFriend Functionscomplex operator +(complex c1,complex c2) return complex(c2.real+c1.real, c2.imag+c1.imag);complex operator -(complex c1,complex c2) return complex(c1.real-c2.real, c1.imag-c2.imag);95SummarizeRun-Time Binding Compile-Time BindingName Overloading, Name Overriding, and Name HidingAbstract Base ClassOperator Overloading96HomeworklP240: 2,5,8,10lP258: 913lP290: 1497

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号