Code:
1#include <iostream>2#include <cstring>3 4 using namespacestd;5 6 classbase{7 Public:8 Virtual voidfunc1 ();9 Virtual voidFunc2 ();Ten voidfunc3 (); One voidFunc4 (); A }; - - voidbase::func1 () { thecout<<"Base func1"<<Endl; - } - - voidBase::func2 () { +cout<<"Base Func2"<<Endl; - } + A voidbase::func3 () { atcout<<"Base func3"<<Endl; - } - - voidBase::func4 () { -cout<<"Base Func4"<<Endl; - } in - classDerived1: Publicbase{ to Public: + voidFunc1 ();//virtual can omit - //Char Func2 () {}; Error, virtual function return type needs to be consistent the voidfunc3 (); * CharFunc4 (); $ };Panax Notoginseng - voidderived1::func1 () { thecout<<"Derived1 func1"<<Endl; + } A the voidderived1::func3 () { +cout<<"Derived1 func3"<<Endl; - } $ $ CharDerived1::func4 () { -cout<<"Derived1 Func4 can change the return type"<<Endl; - } the - classDERIVED2: Publicbase{Wuyi Public: the voidfunc1 (); - }; Wu - voidderived2::func1 () { Aboutcout<<"Derived2 func1"<<Endl; $ } - - intMain () { - ABase *B; + Derived1 De1; theB = &De1; -B->func1 (); $B->func3 (); theB->Func4 (); the De1.func4 (); the theDERIVED2 *PDe2; -PDe2 = (derived2*) &De1; inPde2->func1 (); the the return 0; About the}
Output:
Derived1 func1base func3base func4derived1 Func4 can change the return typeDerived1 func1
Summarize:
1, virtual function must be implemented in the parent class, do not implement can use pure virtual function;
2. The return type of a subclass virtual function must be the same as the return type in the parent class, and the normal function can be different;
3, subclass virtual function if the parameter changes, the virtual attribute disappears.
Virtual functions in C + +