原文出自:http://bbs.csdn.net/topics/390853050 <span style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 15.4px;">@lisong694767315 的回答</span>
</pre><pre name="code" class="cpp">对于多重继承,如果类定义了虚函数,该类及其派生类就要生成一张虚拟函数表。如下继承关系(没有覆盖):
<img src="http://img.bbs.csdn.net/upload/201408/06/1407327509_945978.jpg" alt="" />
在子类Derive实例中的虚函数表:
<img src="http://img.bbs.csdn.net/upload/201408/06/1407327707_736164.jpg" alt="" />
</pre><pre name="code" class="cpp">子类自己定义的虚函数会被放到了第一个基类的虚函数表中。如果子类重写了基类的虚函数,则在虚函数表中,子类函数会覆盖相应的基类函数:
<img src="http://img.bbs.csdn.net/upload/201408/06/1407327922_878725.jpg" alt="" />
</pre><pre name="code" class="cpp">以上继承重写了f()函数,子类实例的虚函数表变为:
<img src="http://img.bbs.csdn.net/upload/201408/06/1407327989_963598.jpg" alt="" />
</pre><pre name="code" class="cpp"><span style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 15.4px;">测试:</span>
<pre name="code" class="cpp">#include <cstdlib>
using namespace std;
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 Base3 {
public:
virtual void f() { cout << "Base3::f" << endl; }
virtual void g() { cout << "Base3::g" << endl; }
virtual void h() { cout << "Base3::h" << endl; }
};
class Derive : public Base1, public Base2, public Base3 {
public:
virtual void f() { cout << "Derive::f" << endl; }
virtual void g1() { cout << "Derive::g1" << endl; }
};
typedef void(*Fun)(void);
int main()
{
Fun pFun = NULL;
Derive d;
int** pVtab = (int**)&d;
//Base1's vtable
pFun = (Fun)pVtab[0][0];
pFun();
pFun = (Fun)pVtab[0][1];
pFun();
pFun = (Fun)pVtab[0][2];
pFun();
//Derive's vtable
pFun = (Fun)pVtab[0][3];
pFun();
//Base2's vtable
pFun = (Fun)pVtab[1][0];
pFun();
pFun = (Fun)pVtab[1][1];
pFun();
pFun = (Fun)pVtab[1][2];
pFun();
//Base3's vtable
pFun = (Fun)pVtab[2][0];
pFun();
pFun = (Fun)pVtab[2][1];
pFun();
pFun = (Fun)pVtab[2][2];
pFun();
system("pause");
return 0;
}
输出:
</pre><pre name="code" class="cpp">Derive::f
Base1::g
Base1::h
Derive::g1
Derive::f
Base2::g
Base2::h
Derive::f
Base3::g
Base3::h
请按任意键继续. . .