如何实现多态向下类型的自动转换?
#include <iostream>
#include <typeinfo>
#include <string>
using namespace std;
class animal
{
public:
virtual void breathe(){ cout << "animal bubble" << endl; }
virtual animal* getThis(){ return this; }
};
class fish : public animal
{
public:
void breathe(){ cout << "fish bubble" << endl; }
void eat(){ cout << "fish eat" << endl; }
animal* getThis(){ return this; }
};
int main()
{
animal *pa;
fish f;
pa = &f;
cout << typeid(pa->getThis()).name() << endl;
cout << typeid(f).name() << endl;
// pa->getThis()->eat();
return 0;
}
//----------------------------------------------------------------------------------------------------------
为什么 typeid(pa->getThis()).name()和 typeid(f).name()返回的类型不一样?
getThis函数返回当前对象的指针,应该是fish*,为什么注释掉那行语句是错误的?
不强制转换类型,怎么才可以让注释掉的那行代码正常运行?