新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > C++类指针指向子类还是基类的判断方法

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

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

// `(*∩_∩*)

本文引用地址:http://www.eepw.com.cn/article/201612/324447.htm

关键词: C++类指针子类基

评论


相关推荐

技术专区

关闭