1. The use of inheritance: Write a class, this class and the previous written class, just add some members or changes to the original member's behavior, you can inherit the original class, the grammar does not expand to say, through the code to write a few sentences summary.
#include <iostream>using namespacestd;classA { Public: Virtual voidFvoid) {cout <<"A ' f (void)!"<<Endl;} Virtual voidVF () {cout <<"A ' VF () running!"<<Endl;}};classD | PublicA { Public: voidFint) {cout <<"B ' f (int)!"<<Endl;} Virtual voidVF () {cout <<"B ' VF () running!"<<Endl;}};intMain () {b b; A&a =b; A*PA; B*PB; A.F (); //A ' f (void)!PA = &b; PA->f ();//A ' f (void)!B.F (3);//B ' f (int)!PA=NewA; PA->VF ();//A ' VF () running! DeletePA; PA=NULL; DeletePA; PA=NewB; PA->VF ();//B ' VF () running! DeletePA; PB=NewB; PB->VF ();//B ' VF () running! PB->a::f ();//A ' f (void)! Pb->b::f (3);//B ' f (int)! DeletePB; return 0;}
The base class pointer creates a subclass object with the same parameter function as the same name, giving precedence to the subclass function.
2. Handle Class
The previous blog post is too cumbersome, a few days ago to re-comb the implementation of the handle class to consider the motive, with a simple handle class to illustrate.
#include <iostream>using namespacestd;classA {protected: intLen; VirtualA * Clone () {return NewA (* This); }Private: intHandlea; FriendclassHandle; Public: A (): Handlea (0) {} A (inta) {Handlea =A;} A (IStream& is) {Read ( is); }; Virtualistream& Read (istream& is); Virtual intSum () {cout <<"A ' sum ()"<< Endl;returnHandlea + -; } Virtual~A () {};}; IStream& A::read (istream& is) { is>>Handlea; return is;}classD | PublicA { Public: B (): Handleb ( -) {} B (intb) {Handleb =b;} B (IStream& is) {Read ( is); } IStream& Read (istream& is); intSum () {cout <<"B ' sum ()"<< Endl;returnHandleb + +; }protected: B* Clone () {return NewB (* This); }//Private & protected both ok!Private: intHandleb;}; IStream& B::read (istream& is) { is>>Handleb; return is;}classHandle { Public: Handle ():p A (0) {} istream& Read (istream& is); Handle (Handle& F) {if(F.PA) pa = F.pa->clone ();ElsePA =0; } Handle&operator= (handle&f) {if(&f! = This) { DeletePA; if(F.PA) PA = f.pa->Clone (); ElsePA =0; } return* This; } intsum () {if(PA)returnPa->sum (); Else{cout <<"Handle ' s sum"<< Endl; PA =0;return the; } } ~handle () {DeletePA;}Private: A*PA;}; IStream& Handle::read (istream& is) { DeletePA; Charch; is>>ch; if(ch = ='a'|| ch = ='A') {PA=NewA is); } Else if(ch = ='b'|| ch = ='B') {PA=NewB is); } Else{PA=0; } return is;}intMain () {Handle F; cout<<"Input A or B?"<<Endl; F.read (CIN); Handle g (f); Handle h=F; cout<< f.sum () <<Endl; cout<< g.sum () <<Endl; cout<< h.sum () <<Endl; return 0; }
C + + Inheritance