C++多态
#pragma once
#include
using namespace std;
class Father
{ public:
virtual void play();
};
#include “Father.h”
void Father::play()
{
cout << “到KTV唱歌” << endl;
}
#pragma once
#include “Father.h”
class Son :public Father
{
void play();
};
#include “Son.h”
void Son::play()
{
cout << “一起打王者” << endl;
}
#include “Father.h”
#include “Son.h”
void party(Father **man,int n) {
for (int i = 0; i < n;i++) {
man[i]->play();
}
}
int main(void) {
Father father;
Son son1, son2;
Father* man[] = {&father,&son1,&son2};
party(man,sizeof(man)/sizeof(man[0]));
system(“pause”);
return 0;
}

本文通过C++代码示例展示了多态的概念和应用,通过基类指针调用派生类的方法实现运行时多态,具体包括父类与子类的定义、方法重写以及多态函数的使用。
1959

被折叠的 条评论
为什么被折叠?



