reinterpret_cast用法详解
重新解释类型(挂羊头,卖狗肉) 不同类型间的互转,数值与指针间的互转
用法: TYPE b = reinterpret_cast ( a ) TYPE必须是一个指针、引用、算术类型、函数指针.
忠告:滥用 reinterpret_cast 运算符可能很容易带来风险。 除非所需转换本身是低级别的,否则应使用其他强制转换运算符之一。
demo 代码(一)
#include <iostream>
using namespace std
;
class Animal
{
public
:
void cry()
{
cout
<< "动物叫" << endl
;
}
};
class Cat
:public Animal
{
public
:
void cry()
{
cout
<< "喵喵" << endl
;
}
};
class Dog
:public Animal
{
void cry()
{
cout
<< "旺旺" << endl
;
}
};
int main(void)
{
int* p
= reinterpret_cast
<int*>(0x999999);
int val
= reinterpret_cast
<int>(p
);
Dog dog1
;
Animal
* a1
= &dog1
;
a1
->cry();
Dog
* dog1_p
= reinterpret_cast
<Dog
*>(a1
);
Dog
* dog2_p
= static_cast
<Dog
*>(a1
);
Cat
* cat2_p
= reinterpret_cast
<Cat
*>(dog1_p
);
Animal a2
= dog1
;
Dog
& dog3
= reinterpret_cast
<Dog
&>(a2
);
dog1_p
->cry();
dog2_p
->cry();
cat2_p
->cry();
system("pause");
return 0;
}
编译:
结语:
时间: 2020-07-02