如何实现多态向下类型的自动转换?

sfxyz7 sfxyz7 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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*,为什么注释掉那行语句是错误的?
不强制转换类型,怎么才可以让注释掉的那行代码正常运行?
...全文
评论 14
收藏 已收藏
分享
返回顶部
sfxyz7
C++ 语言 65,212 成员 250,513 内容