先来看下普通的继承:
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;