專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

C++類指針指向子類還是基類的判斷方法

作者:黃波海   來(lái)源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間: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;  //一個(gè)指向animal的指針
pan=&st;  //把這個(gè)指針換成plant的類空間
fn(pan);//把這個(gè)被替換的指針賦給fn(),它貌似指向了,然后通過(guò)這個(gè)函式指向eat()
}
//函數(shù)中有兩個(gè)類,而且都有eat()函數(shù)最后到底指向哪個(gè)eat()呢!
//答:指向基類。如果想指向子類,辦法是有的!就是把基類的eat()函數(shù)虛化。加virtual前綴即可!

// `(*∩_∩*)

關(guān)閉窗口

相關(guān)文章