从未实例化子类, 只把父类指针强制转化成子类, 子类的方法竟然可用.
搞不明白, 请高手指点.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class animal
{
public:
animal()
{
}
~animal()
{
}
void Breathe()
{
cout << "animal function"<<endl;
}
};
class fish:public animal
{
public:
fish():animal()
{
}
~fish()
{
}
void BB()
{
cout << "fish function" << endl;
}
};
void fun(animal* pAni)
{
fish* pfs = (fish*)(pAni);
if (NULL != pfs)
{
pfs->BB();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
animal ani;
animal* pAni = &ani;
fun(pAni);
return 0;
}
输出结果: fish function