分享

C++类指针指向子类还是基类的判断方法

 共同成长888 2015-07-19

C++类指针指向子类还是基类的判断方法 

#include <iostream.h>

class animal
{
public:
animal()
{
cout<<"hello kitty"<<endl;
}
virtual void eat()
{
cout<<"eat bianbian"<<endl;
}
};
 
class plant:public animal
{
public:
plant()
{
 
}
 void eat()
{
cout<<"haha"<<endl;
}
 
 
};
void fn(animal *pan)
{
pan->eat ();
}
void main()
{
plant st;
animal*pan;  //一个指向animal的指针
pan=&st;  //把这个指针换成plant的类空间
fn(pan);//把这个被替换的指针赋给fn(),它貌似指向了,然后通过这个函式指向eat()
}
//函数中有两个类,而且都有eat()函数最后到底指向哪个eat()呢!
//答:指向基类。如果想指向子类,办法是有的!就是把基类的eat()函数虚化。加virtual前缀即可!

// `(*∩_∩*)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多