为什么要有多态?
#include<iostream>
#include<string>
using namespace std;
//岳不群
class Yuebuqun
{
public:
Yuebuqun (string kongfu)
{
this->kongfu = kongfu;
}
virtual void fight()//virtual表7示修饰的一个成员方法时一个虚函数,和虚继承含义不同
{
cout << "岳不群" << "使出了" << kongfu << "打人" << endl;
}
string kongfu;
};
//林平之类
class Linpingzhi :public Yuebuqun
{
public:
Linpingzhi(string kongfu) :Yuebuqun(kongfu)
{
}
//如果父类中有一个虚函数,子类如果去重写这个函数,
void fight()
{
cout << "林平之" << "使出了" << kongfu << "打人" << endl;
}
};
class Linghuchong :public Yuebuqun
{
public:
Linghuchong(string kongfu) :Yuebuqun(kongfu)
{
}
void fight()
{
cout << "令狐冲" << "使出了" << kongfu << "打人" << endl;
}
};
//在全局提供一个打斗的方法
void fightPeople(Yuebuqun *hero)//Yuebuqun *hero = xiaopp;
{
cout << "调用打人的方法" << endl;
hero->fight();//希望传递进来的如果是子类,调用子类的fight
//希望传递进来的如果是父类,调用父类的fight
//这种行为就是多态行为
}
//多态发生的三个必要条件:
//1.要有继承
//2.要有虚函数重写
//3.父类指针或引用指向子类对象
int main()
{
Yuebuqun xiaoyy("辟邪剑谱");//在栈上开辟的
xiaoyy.fight();
Yuebuqun *xiaoyy1 = new Yuebuqun("辟邪剑谱");//在堆上开辟的
xiaoyy1->fight();
delete xiaoyy1;
Linpingzhi *xiaopp1 = new Linpingzhi("葵花宝典");
xiaopp1->fight();
delete xiaopp1;
Yuebuqun *xiaoyy2 = new Yuebuqun("辟邪剑谱");
Linpingzhi *xiaopp2 = new Linpingzhi("葵花宝典");
Linghuchong *xiaoll = new Linghuchong("独孤九剑");
fightPeople(xiaoyy2);
fightPeople(xiaopp2);
fightPeople(xiaoll);
//编译器默认做了一个安全的处理。编译器认为,不管传递子类对象还是父类对象,
//如果统一执行父类的方法,那么一定会被成功执行。
delete xiaoyy2;
delete xiaopp2;
delete xiaoll;
return 0;
}
总结:
Yuebuqun *hero = xiaopp;
hero->fight();
希望传递进来的如果是子类,调用子类的fight
希望传递进来的如果是父类,调用父类的fight
这种行为就是多态行为
多态发生的三个必要条件:
1.要有继承
2.要有虚函数重写
3.父类指针或引用指向子类对象