#include <iostream>
using namespace std;
class Human
{
private:
public:
//普通函数不具有多态性
void move()
{
cout << "moving moving" << endl;
}
//虚函数,具有多态性
virtual void attack()
{
cout << "attack" << endl;
}
};
class FootMan : public Human
{
private:
public:
//名字隐藏
void move()
{
cout << "action" << endl;
}
//函数的覆盖
virtual void attack()
{
cout << "FootMan attack" << endl;
}
};
class RifleMan : public Human
{
private:
public:
void move()
{
cout << "OOOOK" << endl;
}
virtual void attack()
{
cout << "Fireeeee" << endl;
}
};
class Peasant : public Human
{
private:
public:
void move()
{
cout << "more work" << endl;
}
void work()
{
cout << "work work" << endl;
}
};
int main()
{
Human* ph = new FootMan;
ph->move(); //编译期绑定
ph->attack(); //运行期绑定
delete ph;
ph = new RifleMan;
ph->move(); //编译期绑定
ph->attack(); //运行期绑定
delete ph;
cout << "===============" << endl;
FootMan fm;
RifleMan rm;
Human& rh = fm;
rh.move(); //父类
rh.attack(); //子类
cout << "==============" << endl;
Human* ph2 = new Peasant;
ph2->move();
ph2->attack();
//调用弗雷中没有的函数不能通过编译
//ph2->work();
}
/* 程序运行结果
moving moving
FootMan attack
moving moving
Fireeeee
===============
moving moving
FootMan attack
==============
moving moving
attack
*/
polymorphism、名字隐藏,函数覆盖
最新推荐文章于 2023-10-24 23:39:46 发布