专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

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

作者:黄波海   来源:本站原创   点击数:  更新时间:2014年03月07日   【字体:

#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前缀即可!

// `(*∩_∩*)

关闭窗口

相关文章