




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、C+ Programming CHAPTER 8 INHERITANCE18.1 Introduction8.2 Basic Concepts and Syntax8.3 Public, Private, and Protected Inheritance8.4 Multiple Inheritance 8.5 Constructors and Destructors Under Inheritance8.6 Name Hiding8.7 Virtual Inheritance28.1 IntroductionIn C+, we can build a new class by derivin
2、g the new class from an already existing class. The mechanism for this derivation is inheritance, and the derived class is said to be inherited from the original class.38.1 Introductionsalon cartruckestate carcarvehicle48.1 IntroductionInheritance promotes code reuse because the code in the base cla
3、ss is inherited by the subclass and thus need not be rewritten. You can reuse code by creating new classes, but instead of creating them from scratch, you use existing classes that someone else has built and debugged.58.1 IntroductionInheritance also provides a mechanism to express the natural relat
4、ionships among the components of a program.68.1 Introductionmonkeyliontigerleopardcatbirdanimal78.1 IntroductionInheritance is required for polymorphism in which the particular method to invoke depends on the class to which the object belongs, but the class to which the object belongs is not known u
5、ntil the program is executing.88.2 Basic Concepts and SyntaxSyntax:class DerivedClass:InheritanceMode BaseClasspublic:/protected:/private:/;98.2 Basic Concepts and SyntaxExample:class Penpublic:enum ink Off, On;void set_status( ink );void set_location( int, int );private:int x;int y;ink status;108.2
6、 Basic Concepts and Syntaxclass CPen : public Penpublic:void set_color(int);private:int color;118.2 Basic Concepts and Syntaxint main()CPen pen1;return 0;PenCPenCPen128.2 Basic Concepts and SyntaxRemarks:A) The members, which are public in the base class, are also public in the derived class.B) The
7、private member in a base class is visible only in the base class. 138.3 Public, Private, and Protected InheritancePublic InheritancePublic InheritanceRules:A) The public members and protected members in the base class are also public and protected in the derived class, but the private members in the
8、 base class cant be accessed in the derived class.148.3 Public, Private, and Protected InheritancePublic InheritanceB) The public members and the protected members in the base class can be accessed by the methods of the derived class, but the private members cant be accessed by the methods of derive
9、d class.C) Only the public members in the base class can be accessed by the objects of the derived class.158.3 Public, Private, and Protected InheritancePublic InheritanceExample:class Point/base classpublic:void InitP(float xx=0, float yy=0) X=xx;Y=yy;void Move(float xOff, float yOff) X+=xOff;Y+=yO
10、ff;float GetX() return X;float GetY() return Y;private:float X,Y;168.3 Public, Private, and Protected InheritancePublic Inheritanceclass Rectangle: public Point /derived classpublic:/ new public method of Rectanglevoid InitR(float x, float y, float w, float h)InitP(x,y);W=w;H=h;/invoke the public me
11、thod of base /classfloat GetH() return H;float GetW() return W;private:/ new private members of Rectanglefloat W,H;constructor and destructor of Point are not inherited!178.3 Public, Private, and Protected InheritancePublic Inheritance#include#includeusing namespace std;int main() Rectangle rect;rec
12、t.InitR(2,3,20,10);/access the public members of the base class by object of derived classrect.Move(3,2); coutrect.GetX(), rect.GetY(),rect.GetW(),rect.GetH()endl;return 0;Output:5,5,20,10188.3 Public, Private, and Protected InheritancePublic InheritanceRemark:The default constructor and destructor
13、can not be inherited.198.3 Public, Private, and Protected InheritancePrivate InheritancePrivate InheritanceRules:A) The public members and protected members in the base class are both private in the derived class, but the private members in the base class can not be accessed in the derived class.208
14、.3 Public, Private, and Protected InheritancePrivate InheritanceB) The public members and the protected members in the base class can be accessed by the methods of the derived class, but the private members cant be access by the methods of derived class.C) All the members in the base class cant be a
15、ccessed by the objects of the derived class.21Example:class Rectangle: private Pointpublic:/ new public methods of Rectangle /access the public members of the base classvoid InitR(float x, float y, float w, float h)InitP(x,y);W=w;H=h; /redeclare the interface of base class, why? void Move(float xOff
16、, float yOff) Point:Move(xOff,yOff);float GetX() return Point:GetX();float GetY() return Point:GetY();float GetH() return H;float GetW() return W;private:/ new private members of Rectanglefloat W,H;22#include#includeusing namespace std;int main() /only the members of derived class /can be access by
17、objects of derived classRectangle rect;rect.InitR(2,3,20,10); rect.Move(3,2);coutrect.GetX(), rect.GetY(),rect.GetW (),rect.GetH ()endl;return 0;Output:5,5,10,20238.3 Public, Private, and Protected InheritanceProtected InheritanceProtected InheritanceRules:A) The public members and protected members
18、 in the base class are both protected in the derived class, but the private members in the base class can not be accessed in the derived class.248.3 Public, Private, and Protected InheritanceProtected InheritanceB) The public members and the protected members in the base class can be accessed by the
19、 methods of the derived class, but the private members cant be access by the methods of derived class.C) All the members in the base class cant be accessed by the objects of the derived class.258.3 Public, Private, and Protected InheritanceProtected InheritanceTo the objects of the derived class, pr
20、otected inheritance is the same with private inheritance. To the derived class, protected inheritance is the same with public inheritance.268.3 Public, Private, and Protected InheritanceProtected InheritanceExample:class Aprotected:int x;int main()A a;a.x=5; /wrong278.3 Public, Private, and Protecte
21、d InheritanceProtected InheritanceExample:class A protected:int x;class B: public Apublic:void Function();void B:Function()x=5; /right288.3 Public, Private, and Protected InheritanceProtected Inheritancecant accessprivateprivateprivateprivateprotectedprivateprivatepubliccant accessprotectedprivatepr
22、otectedprotectedprotectedprotectedprotectedpubliccant accesspublicprivateprotectedpublicprotectedpublicpublicpublicin derived classinheritance mode members in base class298.3 Public, Private, and Protected InheritanceProtected InheritanceExample:Ch8-2.text Ch8-2 answer.txt308.3 Public, Private, and
23、Protected InheritanceCompatible RulesCompatible RulesAn object of derived class, which is public inherited from the base class, can be use as a object of base class:A) Objects of base class can be assigned by the object of derived class.B) References of base class can be initialized by the object of
24、 derived class.318.3 Public, Private, and Protected Inheritance Compatible RulesC) Pointers of base class can be assigned by the pointer of derived class.D) Only members of base class can be accessed by the pointers and objects of base class.328.3 Public, Private, and Protected Inheritance Compatibl
25、e RulesExample:class Base;class Derived: public Base;Base b;Derived d;b=d;Derived d;Base &b=d; Derived d;Base *bptr=&d;Derived *dptr;Base *bptr=dptr;338.3 Public, Private, and Protected Inheritance Compatible RulesExample:#include using namespace std;class B0/Base class public:void display()coutB0:d
26、isplay()endl; ;348.3 Public, Private, and Protected Inheritance Compatible Rulesclass B1: public B0public:void display()coutB1:display()endl;class D1: public B1public:void display()coutD1:display()display();358.3 Public, Private, and Protected Inheritance Compatible Rulesvoid main()B0 b0;/object of
27、B0B1 b1;/ object of B1D1 d1;/ object of D1B0 *p;/ pointer of B0p=&b0;/ point to object of B0fun(p);p=&b1;/point to object of B1fun(p);p=&d1;/ point to object of D1fun(p);Output:B0:display()B0:display()B0:display()368.3 Public, Private, and Protected Inheritance Compatible RulesExercise:#include clas
28、s Basepublic: void f()cout “excuting Base:f() n”; int a;class Derived :public Basepublic: void f()cout“executing Derived:f()”; int a;37int main()Base x;x.a=20;x.f();cout“x.a=”x.aendl;Derived y;y.a=40;y.Base:a=60;y.f();y.Base:f();cout“y.a=”y.aendl;cout“y.Base:a=”y.Base:aendl;Base z=y;cout“z.a=”z.aend
29、l;return 0;Output:executing Base:f()x.a=20executing Derived:f()executing Base:f()y.a=40y.Base:a=60z.a=60388.4 Multiple Inheritance You can inherit from one class, so it would seem to make sense to inherit from more than one class at a time. In multiple inheritance, a derived class has multiple base
30、classes.398.4 Multiple Inheritance Syntax:class DerivedClass:InheritanceMode BaseClass1, InheritanceMode BaseClass2, . /;Remark:The rules of inheritance and access dont change from a single to a multiple inheritance hierarchy.40Example:class Apublic:void setA(int);void showA();private:int a;class Bp
31、ublic:void setB(int);void showB();private:int b;class C : public A, private Bpublic:void setC(int, int, int);void showC();private:int c;41void A:setA(int x) a=x; void B:setB(int x) b=x; void C:setC(int x, int y, int z) setA(x); setB(y); c=z; /.int main()C obj;obj.setA(5);obj.showA();obj.setC(6,7,9);
32、obj.showC();/ obj.setB(6); wrong, why?/ obj.showB(); wrong, why?return 0;428.5 Constructors and Destructors Under InheritanceConstructors under InheritanceConstructors under InheritanceRules:A) Constructors of base class cant be inherited.B) Members of derived class should be initialized by its own
33、constructors. Members of base class should be initialized by the constructors of base class.C) The arguments of the constructors of base class should be offered by the constructor of derived class.438.5 Constructors and Destructors Under InheritanceConstructors under InheritanceSingle InheritanceSyn
34、tax:DerivedClass: DerivedClass (ArgumentListOfBase, ArgumentListOfDdrived):BaseClass(ArgumentListOfBase) /;448.5 Constructors and Destructors Under InheritanceConstructors under InheritanceOrder of Constructor calls in Single Inheritance1) Constructors of base class.2) Constructors of data members i
35、n derived class.3) Constructors of derived class.45Example:#includeusing namespace std;class Bpublic:B();B(int i);B();void Print() const;private:int b;B:B()b=0;coutBs default constructor called. endl;B:B(int i)b=i; coutBs constructor called. endl;B:B()coutBs destructor called. endl; void B:Print() c
36、onstcoutbendl; 46class C:public Bpublic:C();C(int i,int j);C();void Print() const;private:int c;C:C()c=0;coutCs default constructor called. endl;C:C(int i,int j):B(i)c=j;coutCs constructor called.endl;C:C()coutCs destructor called.endl; void C:Print() constB:Print();coutcendl; 47void main()C obj(5,6
37、);obj.Print();Output:Bs constructor called.Cs constructor called.56Cs destructor called.Bs destructor called.Question:Whats the effect of “C:C(int i,int j):B(i)”?488.5 Constructors and Destructors Under InheritanceConstructors under InheritanceMultiple InheritanceSyntax:DerivedClass: DerivedClass (A
38、rgumentListOfBase1, ArgumentListOfBaseN,ArgumentListOfDdrived):BaseClass1(ArgumentListOfBase1), BaseClassN(ArgumentListOf BaseN)BaseClassn(ArgumentListOfBaseN) /;498.5 Constructors and Destructors Under InheritanceConstructors under InheritanceArguments Offering Rules:A) If the constructors of base
39、class need no arguments, constructors of derived class can be no arguments.B) If the constructors of base class need arguments, constructors of derived class should offer arguments to them.508.5 Constructors and Destructors Under InheritanceConstructors under InheritanceOrder of Constructor calls in
40、 Multiple Inheritance:1) Constructors of base classes, in order of their declaration.2) Constructors of data members in derived class, in order of their declaration.3) Constructors of derived class.518.5 Constructors and Destructors Under InheritanceConstructors under InheritanceExample:code.txt. co
41、de-answer.txt528.5 Constructors and Destructors Under InheritanceConstructors under InheritanceCopy ConstructorsRules:A) If the default copy constructor is invoked by the object of derived class, the default copy constructor of base class is invoked automatically.B) If there is a user-defined copy c
42、onstructor of derived class, it should offer arguments to the copy constructor of base class.538.5 Constructors and Destructors Under InheritanceConstructors under InheritanceExample:C:C(C &c1):B(c1)/54Example:#include using namespace std;class B1/base class B1public: B1(int i) coutconstructing B1 i
43、endl; ;class B2/ base class B2public: B2(int j) coutconstructing B2 jendl; ;class B3/ base class B3public: B3() coutconstructing B3 *endl; ;55class C: public B2, public B1, public B3 public: C(int a, int b, int c, int d): B1(a),memberB2(d),memberB1(c),B2(b) private:B1 memberB1;B2 memberB2;B3 memberB
44、3;void main()C obj(1,2,3,4); Output:constructing B2 2constructing B1 1constructing B3 *constructing B1 3constructing B2 4constructing B3 *568.5 Constructors and Destructors Under InheritanceDestructors under InheritanceRules:A) Destructors cant be inherited.B) Order of destructors is opposition of c
45、onstructors.57Example:#include using namespace std;class B1/base class B1 public:B1(int i) coutconstructing B1 iendl;B1() coutdestructing B1 endl;class B2/base class B2public:B2(int j) coutconstructing B2 jendl;B2() coutdestructing B2 endl;class B3/base class B3public:B3()coutconstructing B3 *endl;B
46、3() coutdestructing B3 endl;58class C: public B2, public B1, public B3public: C(int a, int b, int c, int d): B1(a),memberB2(d),memberB1(c),B2(b)private: B1 memberB1; B2 memberB2; B3 memberB3;void main() C obj(1,2,3,4); Output:constructing B2 2constructing B1 1constructing B3 *constructing B1 3constr
47、ucting B2 4constructing B3 *destructing B3destructing B2destructing B1destructing B3destructing B1destructing B2598.6 Name HidingIf a derived class adds a member with the same name as the member in the base class, the local member hides the inherited member. 60Example:#include using namespace std;cl
48、ass B1/base classB1 public:int nV;void fun() coutMember of B1endl;class B2/base class B2 public:int nV;void fun() coutMember of B2endl;class D1: public B1, public B2 public:int nV;/same name with base classvoid fun() coutMember of D1endl; /same name with base class;61void main()D1 d1;d1.nV=1; /membe
49、r of D1 is accessedd1.fun(); d1.B1:nV=2;/member of B1 is accessedd1.B1:fun();d1.B2:nV=3;/member of B2 is accessedd1.B2:fun();628.7 Virtual InheritanceAmbiguityAmbiguityIn multiple inheritance, ambiguity is a problem.638.7 Virtual Inheritance AmbiguityExample:class Apublic:void f();class Bpublic:void
50、 f();void g();class C: public A, piblic B public: void g(); void h();Given the declaration:C c1;c1.f(); / wrong, ambiguousc1.g(); / right, namehiding648.7 Virtual Inheritance AmbiguitySolutions to ambiguitySolution1:Scopingc1.A:f()orc1.B:f()658.7 Virtual Inheritance AmbiguitySolution2:Name Hidingcla
51、ss C: public A, piblic B public:void g();void h();void f1()A:f();void f2()B:f();668.7 Virtual InheritanceVirtual Base ClassesVirtual Base ClassMultiple inheritance hierarchies can be complex, which may lead to the situation in which a derived class inherits multiple times from the same indirect base
52、 class.678.7 Virtual InheritanceVirtual Base ClassesExample:class B public:int b;class B1 : public Bprivate:int b1;class B2 : public Bprivate:int b2;class C : public B1,public B2public:int f();private:int d;688.7 Virtual InheritanceVirtual Base ClassesBB1B2C698.7 Virtual InheritanceVirtual Base Clas
53、sesbb1bb2dmembers of Bmembers of Bmembers of B1members of B2members of C708.7 Virtual InheritanceVirtual Base Classesambiguous:C c;c.bc.B:bunambiguous:c.B1:bc.B2:bHow to solve the data redundancy?718.7 Virtual InheritanceVirtual Base ClassesSyntax:class DerivedClass:virtual InheritanceMode BaseClass
54、/Remark:In multiple inheritance hierarchies, derived class has only one single copy of the base class by using the keyword virtual.728.7 Virtual InheritanceVirtual Base ClassesExample:class B private: int b;class B1 : virtual public B private: int b1;class B2 : virtual public B private: int b2;class
55、 C : public B1, public B2 private: float d;C cobj;cobj.b;/there is only one copy of B in C738.7 Virtual InheritanceVirtual Base ClassesBB1B2Cb1b2dB1 members B2 membersC objectbB membersonly one copy of data member and methods 748.7 Virtual InheritanceVirtual Base ClassesExample:D1nV :int nVd:intB1:n
56、V1:intB2:nV2:intfund():voidfun():voidB1nV1 :intB2nV2 :intD1nVd :intfund():void B0nV :intfun()758.7 Virtual InheritanceVirtual Base Classes#include using namespace std;class B0/base class B0 public:int nV;void fun()coutMember of B0endl;class B1: virtual public B0 /virtual inherited from B0 public:int nV1;class B2: virtual public B0 / virtual inherited from B0 public:int nV2;7
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 工作室設(shè)計(jì)與工作環(huán)境優(yōu)化
- 工作中的時(shí)間管理與自律
- 工業(yè)設(shè)計(jì)與產(chǎn)品創(chuàng)新實(shí)踐
- 工業(yè)設(shè)計(jì)創(chuàng)新與技術(shù)趨勢
- 工業(yè)風(fēng)餐廳裝修設(shè)計(jì)思路
- 工作場所中的安全衛(wèi)生規(guī)范
- 工廠企業(yè)火災(zāi)防范與應(yīng)急處理
- 工程機(jī)械結(jié)構(gòu)強(qiáng)度與穩(wěn)定性研究
- 工程質(zhì)量管理中的監(jiān)理職責(zé)與實(shí)施策略
- 工程機(jī)械的故障診斷與維修
- 湛江市2024-2025學(xué)年初三預(yù)測密卷:化學(xué)試題試卷解析含解析
- DB35T 2191-2024 縣級國土空間總體規(guī)劃編審規(guī)程
- AQ 1083-2011 煤礦建設(shè)安全規(guī)范 (正式版)
- 2024年中華人民共和國企業(yè)所得稅年度納稅申報(bào)表(帶公式)20240301更新
- 江蘇省蘇州市常熟市2023-2024學(xué)年五年級下學(xué)期數(shù)學(xué)期末檢測
- 河南省洛陽市理工學(xué)院附中2025屆數(shù)學(xué)高一下期末考試試題含解析
- 珍惜時(shí)間三分鐘演講稿小學(xué)生(23篇)
- 交響音樂賞析智慧樹知到期末考試答案2024年
- 2024中考復(fù)習(xí)必背初中英語單詞詞匯表(蘇教譯林版)
- 大壩模型制作方案
- 2024年北京門頭溝區(qū)社區(qū)工作者招聘筆試參考題庫附帶答案詳解
評論
0/150
提交評論