以前一直以为C++为了兼容C而把虚函数表指针Vptr放在了对象末尾,而且在《inside the C++ object model》里面也是这么描述的。但是我错了,今天愕然发现不是这样的。而且无论是在g++编译器还是在ms的编译器上都不是这样的!
#include <iostream>
#include <cstdlib>
using namespace std;
#ifndef BYTE
#define BYTE char
#endif
#define myMain main
class A{
private:
int _a;
int _b;
public:
A(int a=0,int b=0):_a(a),_b(b){}
virtual ~A(){cout<<"A destructor"<<endl;}
friend ostream &operator<<(ostream& out , const A &a){out<<a._a;return out;}
};
class B : public A{
private:
int b;
public:
virtual ~B(){cout<<"B destructor"<<endl;}
};
int myMain(int argc , char *argv[])
{
A a(12,13);
cout<<a<<endl;
int *b=reinterpret_cast<int*>(&a);
cout<<*b<<endl;
b++;
cout<<*b<<endl;
b++;
cout<<*b<<endl;
system("pause");
return EXIT_SUCCESS;
}
程序的输出为:
12
4463692
12
13
显然上面的为虚表指针的值,下面为成员变量的值,这说明C++中虚表指针是放在对象的开头的!!!