static_cast< char *>和(char *) [英] Difference between static_cast<char*> and (char*)

查看:1025
本文介绍了static_cast< char *>和(char *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题:)

this is my first question :)

我有一个桩文件,我打开它,如下所示;

I have one pile file, and I have open it like shown below ;

ifstream in ( filename,  ios :: binary | ios :: in ) 

$ b $然后,我希望在unsigned int hold中保存2字节数据;

Then, I wish hold 2 byte data in unsigned int hold ;

unsigned int hold;
in . read(static_cast<char *>(&hold), 2); 

对我来说似乎是正确的。但是,当我用

It seems correct to me. However, when I compile it with

g++  -ansi -pedantic-errors -Werror - -Wall  -o main main.cpp 

编译器发出错误

error: invalid static_cast from type ‘unsigned int*’ to type ‘char*’ 

实际上,我已经解决了这个问题通过改变static_cast与(char *),即

Actually, I have solved this problem by changing static_cast with ( char*), that is

unsigned int hold;
in . read((char*)(&hold), 2); 

我的问题是:


  • static_cast< char *> (char *)之间有什么区别?
  • 我不确定是否使用(char *)如果你有足够的知识,你能告诉我这个话题吗?
  • What is the difference(s) between static_cast<char*> and (char*) ?
  • I am not sure whether using (char*) is a safer or not. If you have enough knowledge, can you inform me about that topic ?

注意:如果你有更好的主意,请帮助我,我可以改善我的问题吗?

NOTE : If you have better idea, please help me so that I can improve my question?

推荐答案

static_cast 隐式C风格的转换。如果你试图投射一个与另一个不兼容的实体,则 static_cast 会给你一个编译时间错误,与隐式c风格的转换不同。

static_cast is a safer cast than the implicit C style cast. If you try to cast an entity which is not compatible to another, then static_cast gives you an compilation time error unlike the implicit c-style cast.

static_cast 在这里给你一个错误,因为你想说的是一个 int 并尝试将其放在 char 中,这是不可能的。 int 需要比 char 占用更多的内存,并且无法以安全的方式进行转换。

static_cast gives you an error here because what you are trying to say is take an int and try to fit it in a char, which is not possible. int needs more memory than what char occupies and the conversion cannot be done in a safe manner.

如果你仍然想要实现这一点,你可以使用 reinterpret_cast ,它允许你类型化两种完全不同的数据类型,但它是不安全。

使用 reinterpret_cast 得到的唯一保证是,如果将结果转换回原始类型,您将获得相同的值,但没有其他安全保证。

If you still want to acheive this,You can use reinterpret_cast, It allows you to typecast two completely different data types, but it is not safe.
The only guarantee you get with reinterpret_cast is that if you cast the result back to the original type, you will get the same value, But no other safety guarantees.

这篇关于static_cast&lt; char *&gt;和(char *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆