#include<iostream>
using namespace std;
class TradesPerson
{
public:
virtual void sayHi()
{
cout << "just say hi" << endl;
}
};
class Thinker : public TradesPerson
{
public:
virtual void sayHi()
{
cout << "hi, I am thinker" << endl;
}
};
class Tailor:public TradesPerson
{
public:
virtual void sayHi()
{
cout << "hi, I am tailor" << endl;
}
};
/************************************************************************/
/*有了虚函数一个test函数就搞定了,只需传递的*p用不同子类生成,那么就可以
得到想要的结果,而没有虚函数,有100个派生类,要写100个sayHi函数*/
/************************************************************************/
void test(TradesPerson *p)
{
p->sayHi();
}
int main()
{
int caseTest;
TradesPerson *p;
cin >> caseTest;
while(caseTest)
{
switch(caseTest)
{
case 1:
p = new TradesPerson();
p->sayHi();
break;
case 2:
p = new Thinker();
p->sayHi();
break;
case 3:
p = new Tailor();
p->sayHi();
break;
}
delete p;
cin >> caseTest;
}
return 0;
}
初学CPP虚函数(一)
最新推荐文章于 2024-08-17 01:34:14 发布