C + + methods for executing parent classes
First, we build a project, and then we write our parent class.
People.h:
<span style= "FONT-SIZE:18PX;" > #ifndef people_h#define people_h#include <iostream>using namespace Std;class people{public : void Say_hello ();}; #endif//People_h</span>
People.cpp :
<span style= "FONT-SIZE:18PX;" > #include "People.h" void People::say_hello () { cout << "People:hello world!" << Endl;} </span>
And then here's our sub-category:
Main.h:
<span style= "FONT-SIZE:18PX;" > #ifndef main_h#define main_h#include "People.h" class Main:public people{public : void Say_hello ();}; #endif//Main_h</span>
Main.cpp:
<span style= "FONT-SIZE:18PX;" > #include "Main.h" void Main::say_hello () { cout << "Main:hello world!" << Endl;} </span>
Well, prepare for the job well, and we'll now write our main program:
<span style= "FONT-SIZE:18PX;" > #include "Main.h" int main () { main *p = new Main (); P--Say_hello (); return 0;} </span>
At this point, the main program output is Main:hello world! ;
And we want to output People:hello world in the parent class! How to do it.
We only need to change the Main.cpp of the subclass:
<span style= "FONT-SIZE:18PX;" > #include "Main.h" void Main::say_hello () { People::say_hello ();} </span>
At this point, we are outputting People:hello world! We will use this method to implement the parent class method.
And we're going to have two of them all out? Still as long as the change on the line;
<span style= "FONT-SIZE:18PX;" > #include "Main.h" void Main::say_hello () { People::say_hello (); cout << "Main:hello World" << Endl;} </span>
At this point, when you run the output, you are outputting two Hello world.
In fact, we can output the Hello world of the parent class even if it is not written in the subclass.
All we have to do is write that in the main program.
<span style= "FONT-SIZE:18PX;" > #include "Main.h" int main () { main *p = new Main (); P--People::say_hello (); Delete p; return 0;} </span>
This is also the strength and convenience of C + +. It feels so good.
PS: Day Walk Jian, gentleman to self-improvement.
C/c++:c++ methods to execute the parent class