【虚函数指针与虚函数列表】

当一个类定义了虚函数会隐式的创建一个自己的虚函数指针和虚函数列表。

class Base {

public:   

  virtual void f() { cout<<"Base::f" << endl; }

  virtual void g() { cout<<"Base::g" << endl; }

  virtual void h() { cout<<"Base::h" << endl; }

};


【虚函数指针与虚函数列表】_第1张图片

 

Derive继承了Base,重写了f(),新增了g1()

class Derive:public Base {

public:

  virtual void f() { cout <<"Derive::f"<< endl; }

  void g1() { cout <<"Derive::g1" << endl; }

};

 【虚函数指针与虚函数列表】_第2张图片

多继承:Derive继承了Base1Base1,重写了f()

class Base1 {

public:   

  virtual void f() { cout <<"Base1::f"<< endl; }

  virtual void g() { cout <<"Base1::g"<< endl; }

  virtual void h() { cout <<"Base1::h"<< endl; }

};

class Base2 {

public:   

  virtual void f() { cout <<"Base2::f"<< endl; }

  virtual void g() { cout <<"Base2::g"<< endl; }

  virtual void h() { cout <<"Base2::h"<< endl; }

};

class Derive:public Base1, public Base2 {

public:   

  virtual void f() { cout <<"Derive::f"<< endl; }

};

【虚函数指针与虚函数列表】_第3张图片

 

Derive d;

Base1*b1 =&d;

Base2*b2 =&d;

b1->f();//Derive::f()

b2->f();//Derive::f()

b1->g();//Base1::g()

b2->g();//Base2::g()

你可能感兴趣的:(【虚函数指针与虚函数列表】)