码迷,mamicode.com
首页 > 编程语言 > 详细

c++之虚函数virtual , overriding , overwrite

时间:2015-04-16 12:25:31      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

先来看下普通的继承:

class Instrument{
public:
    void play() const{
        cout<<"Instrument::play"<<endl;
    }
};

class Wind : public Instrument{
public:
    void play() const{
        cout<<"Wind::play"<<endl;
    }
};

    Instrument* instrumentObj = new Instrument();
    instrumentObj->play();        //output: Instrument::play

    Wind* windObj = new Wind();
    windObj->play();            //output: Wind::play

    Instrument* windInsObj = new Wind();    //子类对象指向父类的指针
    windInsObj->play();            //output: Instrument::play

    //Wind* InsWindObj = new Instrument();// wrong !父类对象不能指向子类的指针    

 

以下是虚函数的继承:

class Instrument{
public:
    virtual void play() const{
        cout<<"Instrument::play"<<endl;
    }
};

class Wind : public Instrument{
public:
    void play() const{
        cout<<"Wind::play"<<endl;
    }
};
  Instrument* instrumentObj = new Instrument();
    instrumentObj->play();        //output: Instrument::play

    Wind* windObj = new Wind();
    windObj->play();            //output: Wind::play

    Instrument* windInsObj = new Wind();    //子类对象指向父类的指针
    windInsObj->play();            //output: Wind::play

    //Wind* InsWindObj = new Instrument();// wrong !父类对象不能指向子类的指针

 

 

纯虚函数和抽象类

纯虚函数使用关键字virtual 并在函数最后加上=0.eg:virtual void fun()=0;

 

c++之虚函数virtual , overriding , overwrite

标签:

原文地址:http://www.cnblogs.com/alazalazalaz/p/4431585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!