• 專注電子技術學習與研究
    當前位置:單片機教程網 >> 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前綴即可!

    // `(*∩_∩*)

    關閉窗口

    相關文章

    亚洲一区二区制服在线|在绩专区欧美自拍日韩|青春娱乐网97超碰人人射|在线观看国产网址你懂的