STATIC_CAST VERSUS REINTERPRET_CAST
static_cast 和 reinterpret_cast 操作符修改了操作数类型. 它们不是互逆的; static_cast 在编译时使用类型信息执行转换, 在转换执行必要的检测(诸如指针越界计算, 类型检查). 其操作数相对是安全的. 另一方面, reinterpret_cast 仅仅是重新解释了给出的对象的比特模型而没有进行二进制转换, 例子如下:
int n=9; double d=static_cast < double > (n);
上面的例子中, 我们将一个变量从 int 转换到 double. 这些类型的二进制表达式是不同的. 要将整数 9 转换到 双精度整数 9, static_cast 需要正确地为双精度整数 d 补足比特位. 其结果为 9.0. reinterpret_cast 的行为却不同:
int n=9;
double d=reinterpret_cast<double & > (n);
这次, 结果有所不同. 在进行计算以后, d 包含无用值. 这是因为 reinterpret_cast 仅仅是复制 n 的比特位到 d, 没有进行必要的分析.
因此, 你需要谨慎使用 reinterpret_cast.
有没有方法,类已实例化后,得到类中非静态成员函数在内存中的地址?
#include <iostream.h>
class AAA
{
public:
int a;
int b;
protected:
private:
};
void main()
{
AAA b;
int AAA::* AAA_b_Offset = &AAA::b;
int AAA_b_Address = reinterpret_cast<int>(reinterpret_cast<int*>(&b))+*(int*)&AAA_b_Offset;
cout<<AAA_b_Address;
}