例1:虚函数表的结构
以下是代码及运行结果:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void f() { cout << "Base::f" << endl; }
virtual void g() { cout << "Base::g" << endl; }
virtual void h() { cout << "Base::h" << endl; }
};
typedef void (*Fun)(void);
int main()
{
Base b;
Fun pFun = NULL;
cout << "对象地址:" << (int*)(&b) << endl;
cout << "虚函数表地址:" << (int*)*(int*)(&b) << endl;
cout << "虚函数表 — 第1个函数地址:" << (int*)*((int*)*(int*)(&b) + 0) << endl;
cout << "虚函数表 — 第2个函数地址:" << (int*)*((int*)*(int*)(&b) + 1) << endl;
cout << "虚函数表 — 第3个函数地址:" << (int*)*((int*)*(int*)(&b) + 2) << endl;
// Invoke the first virtual function
pFun = (Fun)*((int*)*(int*)(&b) + 0);
pFun();
pFun = (Fun)*((int*)*(int*)(&b) + 1);
pFun();
pFun = (Fun)*((int*)*(int*)(&b) + 2);
pFun();
return 0;
}
using namespace std;
class Base
{
public:
virtual void f() { cout << "Base::f" << endl; }
virtual void g() { cout << "Base::g" << endl; }
virtual void h() { cout << "Base::h" << endl; }
};
typedef void (*Fun)(void);
int main()
{
Base b;
Fun pFun = NULL;
cout << "对象地址:" << (int*)(&b) << endl;
cout << "虚函数表地址:" << (int*)*(int*)(&b) << endl;
cout << "虚函数表 — 第1个函数地址:" << (int*)*((int*)*(int*)(&b) + 0) << endl;
cout << "虚函数表 — 第2个函数地址:" << (int*)*((int*)*(int*)(&b) + 1) << endl;
cout << "虚函数表 — 第3个函数地址:" << (int*)*((int*)*(int*)(&b) + 2) << endl;
// Invoke the first virtual function
pFun = (Fun)*((int*)*(int*)(&b) + 0);
pFun();
pFun = (Fun)*((int*)*(int*)(&b) + 1);
pFun();
pFun = (Fun)*((int*)*(int*)(&b) + 2);
pFun();
return 0;
}
输出结果:
对象地址:0012FF7C
虚函数表地址:0046C0AC
虚函数表 — 第1个函数地址:0040122B
虚函数表 — 第2个函数地址:004010AF
虚函数表 — 第3个函数地址:004012AD
Base::f
Base::g
Base::h
Press any key to continue
以下是图解:
例2:以下程序的运行结果是什么?
#include <iostream>
using namespace std;
class A
{
public:
virtual void f() { cout << "A::f" << endl; }
virtual void g() { cout << "A::g" << endl; }
void h() { cout << "A::h" << endl; }
};
class B : public A
{
public:
void f() { cout << "B::f" << endl; }
virtual void g() { cout << "B::g" << endl; }
void h() { cout << "B::h" << endl; }
};
int main()
{
A *pa = new B();
pa->f(); //B::f
pa->g(); //B::g
pa->h(); //A::h
printf("\n");
A *paa = new A();
paa->g(); //A::g
B *pbb = (B *)paa;
pbb->g(); //A::g
printf("\n");
delete paa, pbb;
paa = new B();
paa->g(); //B::g
pbb = (B *)paa;
pbb->g(); //B::g
return 0;
}
using namespace std;
class A
{
public:
virtual void f() { cout << "A::f" << endl; }
virtual void g() { cout << "A::g" << endl; }
void h() { cout << "A::h" << endl; }
};
class B : public A
{
public:
void f() { cout << "B::f" << endl; }
virtual void g() { cout << "B::g" << endl; }
void h() { cout << "B::h" << endl; }
};
int main()
{
A *pa = new B();
pa->f(); //B::f
pa->g(); //B::g
pa->h(); //A::h
printf("\n");
A *paa = new A();
paa->g(); //A::g
B *pbb = (B *)paa;
pbb->g(); //A::g
printf("\n");
delete paa, pbb;
paa = new B();
paa->g(); //B::g
pbb = (B *)paa;
pbb->g(); //B::g
return 0;
}