混淆了调用派生类虚函数的方式

Kun*_*nal -4 c++ virtual

在下面的代码中,我无法理解调用派生类的虚方法的方式.此外,任何人都可以建议一个源,其中虚拟功能的概念用非常基本的方法图解说明.

class Base1
{
  virtual void fun1() { cout << "Base1::fun1()" << endl; }
  virtual void func1() { cout << "Base1::func1()" << endl; }
};


class Base2 
{
  virtual void fun1() { cout << "Base2::fun1()" << endl; }
  virtual void func1() { cout << "Base2::func1()" << endl; }
};


class Base3 
{
    virtual void fun1() { cout << "Base3::fun1()" << endl; }
    virtual void func1() { cout << "Base3::func1()" << endl; }
};

class Derive : public Base1, public Base2, public Base3
{

public:

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

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


typedef void(*Fun)(void);

int main()
{
  Derive obj;
  Fun pFun = NULL;

  // calling 1st virtual function of Base1
  pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+0);
  pFun();

  // calling 2nd virtual function of Base1
  pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+1);
  pFun();

  // calling 1st virtual function of Base2
  pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+0);

  pFun();

  // calling 2nd virtual function of Base2

  pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+1);
  pFun();

  // calling 1st virtual function of Base3
  pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+0);
  pFun();

  // calling 2nd virtual function of Base3
  pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+1);

  pFun();

  // calling 1st virtual function of Drive
  pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+2);
  pFun();

  // calling 2nd virtual function of Drive
  pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+3);
  pFun();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

继承图如下所示:

Base1  Base2  Base3

  \      |      /
   \     |     /
    \    |    /
     \   |   /

      Derived
Run Code Online (Sandbox Code Playgroud)

没有明确的功能Derived::func1().Morover,virtual关键字是一个红色的鲱鱼,因为Derived实际上并没有覆盖任何东西.所以唯一的问题是如何调用各种基本函数.这是如何做:

Derived x;

// x.func1(); // Error: no unambiguous base function

x.Base1::func1();
x.Base2::func1();
x.Base3::func1();
Run Code Online (Sandbox Code Playgroud)

如果你真的要覆盖 func1(),那么故事就完全不同了Derived.