C++执行父类的方法
首先,我们建立一个工程,再来写我们的父类。
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>
再来就是我们的子类:
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>
好,准备工作做好了,我们现在来写好我们的主程序:
<span style="font-size:18px;">#include "Main.h"
int main()
{
Main *p = new Main();
p -> say_hello();
return 0;
}
</span>
此时,主程序输出的是Main:hello world !;
而我们想要输出父类中的People:hello world !要怎样做呢。
我们只需要改改子类的Main.cpp:
<span style="font-size:18px;">
#include "Main.h"
void Main::say_hello(){
People::say_hello();
}</span>
此时,我们输出的就是People:hello world !;我们就用这个方法来实行父类的方法。
而我们要两个都输出呢?仍然只要改改就行;
<span style="font-size:18px;">
#include "Main.h"
void Main::say_hello(){
People::say_hello();
cout << "Main: hello world !" << endl;
}
</span>
此时,在运行输出时,就是输出两个hello world 了。
其实,我们即使,不在子类中写,也是能输出父类的hello world的。
我们只需要在主程序中这么写就行了。
<span style="font-size:18px;">
#include "Main.h"
int main()
{
Main *p = new Main();
p -> People::say_hello();
delete p;
return 0;
}
</span>
这也是C++的强力和方便之处。让人感觉很爽。
PS:天行健,君子以自强不息。