一、多态的概念
多态:同样的调用行为,表现出不同的表现形态
二、江湖恩怨
不加virtual 关键字和加上virtual 关键字的区别
#include <iostream>
using namespace std;
class Boss
{
private:
static Boss *Instance;
Boss(){};
public:
static Boss* GetInstance()
{
if (NULL == Instance)
{
Instance = new Boss();
}
return Instance;
}
int fight()
{
return 10;
}
};
Boss *Boss::Instance = NULL;
class Master
{
public:
virtual int eightswordkill()
{
return 8;
}
};
class NewMaster : public Master
{
public:
virtual int eightswordkill()
{
return Master::eightswordkill() * 2;
}
};
int PK(Master *p, Boss *q)
{
int i = p->eightswordkill();
int j = q->fight();
if (i < j)
{
cout<<"Master is killed."<<endl;
}else
{
cout<<"Boss is killed."<<endl;
}
return 0;
}
int main()
{
Master master;
Boss *boss = Boss::GetInstance();
NewMaster newmaster;
PK(&master, boss);
PK(&newmaster, boss);
return 0;
}
本文探讨了C++中的多态概念,通过实例展示了不加virtual关键字和加上virtual关键字的区别,深入理解类继承和虚函数的作用。
765

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



