#include <iostream>
using namespace std;
class employee{
public:
virtual void salary(){
cout<<"employee salary"<<endl;
}
};
class programmer:public employee{
public:
void salary()
{
cout<<"programmer salary"<<endl;
}
void bonus()
{
cout<<"programmer bonus"<<endl;
}
};
void payroll(employee *pe)
{
programmer *pm=dynamic_cast<programmer*>(pe);
if(pe)
{
pm->bonus();
}
else
{
pe->salary();
}
};
void payroll(employee& pe)
{
try{
programmer& pm=dynamic_cast<programmer&>(pe);
pm.bonus();
}
catch(exception e)
{
cout<<e.what()<<endl;
}
};
int main()
{
employee *pe=new programmer;
payroll(pe);
employee& pe2=*pe;
payroll(pe2);
employee pe3;
payroll(pe3);
return 0;
}
注意因为不存在空引用,所以,不能比较结果是不是0来检验是否成功。
通过异常机制。