关于virtual table与vptr的疑问,该怎么处理
关于virtual table与vptr的疑问
#include <iostream>
using namespace std;
class Test
{
virtual void fun1()
{
cout << "Test::fun1" << endl;
}
};
int main()
{
Test obj;
cout << "VPTR's Address " << (int*)(&obj+0) << endl;//VPTR's Address 0012FF7C
cout << "VPTR's Value " << (int*)*(int*)(&obj+0) << endl;//VPTR's Value 0046F040
//cout << "VPTR's Address " << &obj+0<< endl; //VPTR's Address 0012FF7C
//cout << "VPTR's Value " << *(int*)(&obj+0) << endl;//VPTR's Value 4649024
return 0;
}
如我上面的程序,为什么每次都要将地址转换成(int *),这里有什么说道?
对(int*)(&obj+0)与&obj+0的值是一样的
而(int*)*(int*)(&obj+0)与*(int*)(&obj+0) 为什么又不一样了?
------解决方案--------------------
没什么说道,转换完了用cout输出会识别成是指针从而给你显示成十六进制而已。
如果有虚函数的话虚表的地址始终存储在对象的最头部,长度4个字节(x86)或8个字节(x64),虚表的地址指向的是基类的虚函数以及自身重写的虚函数。根据编译器不同结尾标志不同而已。
#include <iostream>
using namespace std;
class Test
{
virtual void fun1()
{
cout << "Test::fun1" << endl;
}
};
int main()
{
Test obj;
cout << "VPTR's Address " << (int*)(&obj+0) << endl;//VPTR's Address 0012FF7C
cout << "VPTR's Value " << (int*)*(int*)(&obj+0) << endl;//VPTR's Value 0046F040
//cout << "VPTR's Address " << &obj+0<< endl; //VPTR's Address 0012FF7C
//cout << "VPTR's Value " << *(int*)(&obj+0) << endl;//VPTR's Value 4649024
return 0;
}
如我上面的程序,为什么每次都要将地址转换成(int *),这里有什么说道?
对(int*)(&obj+0)与&obj+0的值是一样的
而(int*)*(int*)(&obj+0)与*(int*)(&obj+0) 为什么又不一样了?
------解决方案--------------------
没什么说道,转换完了用cout输出会识别成是指针从而给你显示成十六进制而已。
如果有虚函数的话虚表的地址始终存储在对象的最头部,长度4个字节(x86)或8个字节(x64),虚表的地址指向的是基类的虚函数以及自身重写的虚函数。根据编译器不同结尾标志不同而已。