常说虚函数,但是现在我还不了解什么是虚函数,怎么直观地表白?它和常用的函数有何本质的区别?

解决方案 »

  1.   

    实现动态连编,即执行哪个函数不是编译时就决定的,而是运行时才绑定的.for example:
    比如你想定以几个类来表现狗和猫的行为,它们都会叫,但是叫声不同(猫为喵喵,狗为汪汪),你就定义一个基类:
    class Animal
    {
       public:
          virtual  void voice();
    };
    class Dog
    {
      public:
          void  voice(){//定义狗的行为}
    };
    class Cat
    {
        public:
           void voice(){//定义猫的行为}
    };
    这样的话当你这样用的时候:
    Dog d;
    Cat c;
    Animal * pa;
    pa=&d;
    pa->voice();//调用Dog::voice()
    pa=&c;
    pa->voice();//调用Cat::voice()
    你可以通过调用同一个函数而视指针所指对象的不同而调用不同版本的函数。
      

  2.   

    主要是为了能通过基类的指针调用派生类的同名函数(方法):class Base{
      Base(){}
      ~Base(){}
      virtual void DeclareIt(){AfxMessageBox("I am in Class Base");}
    }class Derived : public Base {
      Derived(){}
      ~Derived(){}
      virtual void DeclareIt(){AfxMessageBox("I am in Class Derived");}
    }void DoSomething(Base* p){
      p->DeclareIt();
    }main(){
      Base a;
      Derived b;
      DoSomething(&a);  // 调用Base的DeclareIt()
      DoSomething(&b);  // 调用Derived的DeclareIt()  Base* p[2];
      p[0] = new Base;
      p[1] = new Derived;
      for(int i=0; i<2; i++){
        p[i]->DeclareIt();  // i=0时将调用Base::DeclareIt, i=1 调用 Derived::DeclareIt
      }
    }