reinterpret_cast(&st)

哎呦哀木涕 2008-03-23 11:26:01
reinterpret_cast<char*>(&st)
是什么意思
...全文
464 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wwwwfly 2008-03-24
  • 打赏
  • 举报
回复
1)static_cast(a)
将地址a转换成类型T,T和a必须是指针、引用、算术类型或枚举类型。
表达式static_cast< T > ( a ) a的值转换为模板中指定的类型T。在运行时转换过程中,不进行类型检查来确保转换的安全性。
2)dynamic_cast(a)
完成类层次结构中的提升。T必须是一个指针、引用或无类型的指针。a必须是决定一个指针或引用的表达式。
表达式dynamic_cast< T >( a ) 将a值转换为类型为T的对象指针。如果类型T不是a的某个基类型,该操作将返回一个空指针。
3)const_cast(a)
去掉类型中的常量,除了const或不稳定的变址数,T和a必须是相同的类型。
表达式const_cast< T >( a )被用于从一个类中去除以下这些属性:const, volatile, 和 __unaligned。
4)reinterpret_cast(a)
任何指针都可以转换成其它类型的指针,T必须是一个指针、引用、算术类型、指向函数的指针或指向一个类成员的指针。
表达式reinterpret_cast< T >( a )能够用于诸如char* 到 int*,或者One_class* 到 Unrelated_class*等类似这样的转换,因此可能是不安全的。
ttkk_2007 2008-03-24
  • 打赏
  • 举报
回复
说简单点,就是把st的地址解释为char*,安不安全你自己看看吧
星羽 2008-03-24
  • 打赏
  • 举报
回复
The reinterpret_cast operator also allows any integral type to be converted into any pointer type and vice versa. Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.

The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable.

The reinterpret_cast operator cannot cast away the const, volatile, or __unaligned attributes. See const_cast Operator for information on removing these attributes.

The reinterpret_cast operator converts a null pointer value to the null pointer value of the destination type.

One practical use of reinterpret_cast is in a hash function, which maps a value to an index in such a way that two distinct values rarely end up with the same index.

taodm 2008-03-24
  • 打赏
  • 举报
回复
楼主啊,备一本《C++ Primer》吧,不认识的东西就去查它的书后索引表。
野男孩 2008-03-24
  • 打赏
  • 举报
回复
主要是涉及数据在内存中的表示。

看看下面的代码:

#include <iostream>
using namespace std;

void main()
{
int i = 875770417; //在内存中的表示从低位到高位依次是0x31 0x32 0x33 0x34
cout<<i<<" ";
char* p = reinterpret_cast<char*>(&i);
for(int j=0; j<4; j++)
cout<<p[j];
cout<<endl;

float f = 0.00000016688933; //在内存中的表示从低位到高位依次也是0x31 0x32 0x33 0x34
cout <<f<<" ";
p = reinterpret_cast<char*>(&f);
for(j=0; j<4; j++)
cout<<p[j];
cout<<endl;
}


不管是int型的i还是float型的f,经过reinterpret_cast<char*>(&addr)的转换后,输出都是"1234"
数据的表示相同,就看编译器怎么来解释数据,也就是语义表达的问题。
reinterpret_cast的转换就是不理会数据本来的语义,而重新赋予它char*的语义。
arong1234 2008-03-23
  • 打赏
  • 举报
回复
为什么不MSDN一下,这个问题太简单了,MSDN就可以告诉你,不需要CSDN
AlwaysSLH 2008-03-23
  • 打赏
  • 举报
回复
c++里的强制类型转换

64,701

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧