C/C++: C++中reinterpret_cast 含义

来源:互联网 发布:淘宝天猫评论采集工具 编辑:程序博客网 时间:2024/05/22 00:19


C++编程思想中是这么说的: r e i n t e r p r e t _ c a s t假设一个对象仅仅是一个比特模式,它可以被当作完全不同的对象对待(为了某种模糊的目的)


reinterpret_cast 是流氓


//============================================================================
// Name        : reinterpret_cast.cpp
// Author      : zhaog
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

#include <string.h>
#include <fstream>

ofstream out("reinterp.out");


class X
{
    enum {sz = 5};
    int a[sz];

public:
    X(){memset(a, 0, sz*sizeof(int));}
    virtual void f(){}
    int membsize(){return sizeof(a);}
    friend ostream& operator<<(ostream& os, const X& x)
    {
        for (int i = 0; i < sz; i++)
            os << x.a[i] << ' ';
        return os;
    }
};


int main() {
    X x;
    cout << x <<endl;

    int *xp = reinterpret_cast<int *>(&x);
    //xp[0] 为 vptr
    xp[1] = 47;

    cout<< x << endl;

    X x2;
    const int vptr_size = sizeof(X) - x2.membsize(); //计算vptr指针
    long l = reinterpret_cast<long>(&x2);
    l+= vptr_size; //成员变量位置
    xp = reinterpret_cast<int*>(l);
    xp[0] =47;
    cout<<x2<<endl;

    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}


0 0
原创粉丝点击