C Zhong Fu Factory Learning Note / Heiyeluren Learn the most object-oriented object-oriented object-oriented objects: package, inherit, polymorphism, learning polymorphism, first involved is the virtual function, I I record some ideas that I learned the virtual function. The virtual function is to implement a function of some feature. The virtual function can only be a member function in the class, and cannot be a static member. Use the keyword virtual to use the change function in the class is a virtual function. The virtual function is to achieve object-oriented polymorphism, using virtual functions and polymorphism to simplify code length, support simpler order, easy to debug, maintenance. Definition method of virtual function: class a {public: Virtual void fun (); // define virtual function}; void a :: fun () {...} // Member Function Describe Top A virtual function is defined, and then A specific description of the function outside the class. In the inheritance of the class, when a virtual function is declared in the base class, even if there is no virtual function in the derived class, then in the later inheritance structure is a virtual function, of course, if there is multiple inheritance, at each derived class It is recommended to explicitly declare each virtual function. In order to illustrate the application in the derived class, I wrote the code for code: /Test.cpp//code by Heiyeluren # include "stdio" Class CBase {public: virtual void vfoo () {Printf ("vfoo from CBase / N ");}; void foo () {Printf (" foo from cbease / n ");}};
Class CDERIVD: PUBLIC CBASE {PUBLIC: Virtual Void Vfoo () {Printf ("vfoo from cderivd / n");}; void foo () {Printf ("foo from cderivd / n");};
INT Main (int Argc, char * argv []) {CBase * PBase = new cderivd (); pBase-> foo (); // non-virtual function, based on which FOO is called according to the pointer type, this pointer type is CBASE, So calling CBase :: foo () PBase-> vfoo (); // virtual function, calling is a Vfoo delete PBASE that derived class;
CDerivd * pd = new cderivd (); // Non-virtual function, this type pointer type is cderivd *, so CDERIVD:: foo (); pd-> vfoo (); delete Pd;
CDerivd D; D.FOO (); D.Vfoo (); (CBASE) D) .foo (); // Cut D to CBASE, at this time, the foo is foo or vfoo will be Base ( (CBASE) D) .vfoo ();