2021-02-12
作者:互联网
回头又看了一下C++的多态概念 之前学习的时候没理解
大概是在C++过程中你使用父类指针和子类指针调用一个函数时其调用的函数是不相同的。
下面我通过一段代码加强记忆
#include <iostream>
#include <string>
using namespace std;
class Yuebuqun
{
public:
Yuebuqun( string kongfu)
{
this->kongfu = kongfu;
}
virtual void fight()//这里是关键定义fight函数为虚函数在子类函数重写该函数在不同指针调用时体现的功能不同,这就是简单的体现了多态。
{
cout << "岳不群" << "使出了" << kongfu << "打人" << endl;
}
private:
string kongfu;
};
class Linpingzhi:public Yuebuqun
{
public:
Linpingzhi(string kongfu):Yuebuqun(kongfu){}
void fight()
{
cout << "林平之" << "使用了" << kongfu << "打人" << endl;
}
private:
string kongfu;
};
int main()
{
Yuebuqun* xiaoyy = new Yuebuqun("葵花宝典");
xiaoyy->fight();
Linpingzhi* xiaopp = new Linpingzhi("僻邪剑谱");
xiaopp->fight();
delete xiaopp;delete xiaoyy;
}
标签:02,12,函数,kongfu,Linpingzhi,Yuebuqun,fight,2021,xiaoyy 来源: https://blog.csdn.net/weixin_50635790/article/details/113795646