您的位置:首页 > 编程语言 > C语言/C++

C++中虚表指针的存放位置

2013-07-27 14:03 225 查看
以前一直以为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++中虚表指针是放在对象的开头的!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: