您的位置 首页 数字

C++类指针指向子类仍是基类的判别办法

includeiostreamh>classanimal{public:animal(){couthellokittyendl;}virtualvoideat(){couteatbianbian

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

// `(*∩_∩*)

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/zhishi/shuzi/317636.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部