#include <iostream> #pragma hdrstop using std::cout; using std::endl; //--------------------------------------------------------------------------- #pragma argsused //--------------------------------------------------------------------------- class Base { public: Base() { }; virtual void DisplayMessage() { cout << "Displaying Message from an object of Base class" << endl; }; }; //--------------------------------------------------------------------------- class DerivedFirst : public Base { public: DerivedFirst() { }; void DisplayMessage() { cout << "Displaying Message from an object of DerivedFirst class" << endl; } }; //--------------------------------------------------------------------------- class DerivedSecond : public Base { public: DerivedSecond() { }; void DisplayMessage() { cout << "Displaying Message from an object of DerivedSecond class" << endl; } }; //--------------------------------------------------------------------------- class DerivedThird : public Base { public: DerivedThird() { }; }; //--------------------------------------------------------------------------- int main() { // create a base class object Base* bc = new Base(); bc->DisplayMessage(); // delete the base class object and assign it to DerivedFirst object delete bc; bc = new DerivedFirst(); bc->DisplayMessage(); // delete the base class object and assign it to DerivedSecond object delete bc; bc = new DerivedSecond(); bc->DisplayMessage(); // delete the base class object and assign it to DerivedThird object delete bc; bc = new DerivedThird(); bc->DisplayMessage(); delete bc; return EXIT_SUCCESS; } //---------------------------------------------------------------------------
虚函数主要作用:用基类声明的指针(Base* bc),指向派生类,如果派生类中有与基类中相同的方面就调用子类的方法,如果子类没有该方面,就调用基类自身的方法。
基类中如果不加virtual 关键字,用用基类声明的指针,调用函数时只能调用基类自身的函数。