65,187
社区成员




//虚函数表里边保存的不一定是虚函数的地址.cpp
//2010.8.19
//参考:http://topic.csdn.net/u/20091128/14/5a9ff412-560e-4214-8716-e269295f7028.html
/*分析:通过最后的输出结果可以发现,通过Derived类的虚函数表调用所有的虚函数,发现第一张虚函数表的输出1和第二张虚函数表的输出4它们是同一个函数的输出,
在虚函数表项上的值却是不同的。如果虚函数表上的项的值都是虚函数的地址,那么Derived的两张表里边用于调用show()函数的表项的值应该是相同的,但事实上它们不同。
这说明,虚函数表里边保存的未必就是虚函数的地址。这种情况在之前一直没有遇到过(或者没注意到),那么那两个不同的值哪一个才是Derived::show()函数的地址呢?
反汇编分析。。
//Code::Blocks VS2005/2008
*/
#include <iostream>
using namespace std;
class BaseA
{
public:
virtual void show()
{
cout << "BaseA::show()" << endl;
}
virtual void showAA()
{
cout << "BaseA::showAA()" << endl;
}
};
class BaseB
{
public:
virtual void show()
{
cout << "BaseB::show()" << endl;
}
virtual void showBB()
{
cout << "BaseB::showBB()" << endl;
}
};
class Derived : public BaseA, public BaseB
{
public:
/*重写*/
void show()
{
cout << "Derived::show()" << endl;
}
virtual void showD()
{
cout << "Derived::showD()" << endl;
}
};
int main()
{
typedef void (__thiscall *Fun)(void*pThis);//非常重要
BaseA aobj;
BaseB bobj;
Derived dobj;
/*BaseA对象*/
int** p = (int**)&aobj;
cout << "-----BaseA类的对象-----" << endl;
cout << "1 BaseA:\t" << (int*)p[0][0] << "\t"; ((Fun)p[0][0])(p);
cout << "2 BaseA:\t" << (int*)p[0][1] << "\t"; ((Fun)p[0][1])(p);
cout << endl;
/*BaseB对象*/
p = (int**)&bobj;
cout << "-----BaseB类的对象-----" << endl;
cout << "1 BaseB:\t" << (int*)p[0][0] << "\t"; ((Fun)p[0][0])(p);
cout << "2 BaseB:\t" << (int*)p[0][1] << "\t"; ((Fun)p[0][1])(p);
cout << endl;
/*Derived对象的第一个虚函数表指针所指向的虚函数表*/
p = (int**)&dobj;
cout << "-----Derived类的对象-----" << endl;
cout << "1 Derived:\t" << (int*)p[0][0] << "\t"; ((Fun)p[0][0])(p);
cout << "2 Derived:\t" << (int*)p[0][1] << "\t"; ((Fun)p[0][1])(p);
cout << "3 Derived:\t" << (int*)p[0][2] << "\t"; ((Fun)p[0][2])(p);
cout << endl;
/*Derived对象的第二个虚函数表指针所指向的虚函数表*/
p = (int**)((int*)(&dobj)+1);
cout << "4 Derived:\t" << (int*)p[0][0] << "\t"; ((Fun)p[0][0])(p);
cout << "5 Derived:\t" << (int*)p[0][1] << "\t"; ((Fun)p[0][1])(p);
system("pause");
return 0;
}
/*
-----BaseA类的对象-----
1 BaseA: 00401320 BaseA::show()
2 BaseA: 00401350 BaseA::showAA()
-----BaseB类的对象-----
1 BaseB: 004013A0 BaseB::show()
2 BaseB: 004013D0 BaseB::showBB()
-----Derived类的对象-----
1 Derived: 00401440 Derived::show()
2 Derived: 00401350 BaseA::showAA()
3 Derived: 00401470 Derived::showD()
4 Derived: 00405430 Derived::show()
5 Derived: 004013D0 BaseB::showBB()
*/