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

以前一直以为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++中虚表指针是放在对象的开头的!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值