简单的c ++指针铸造 [英] Simple c++ pointer casting

查看:159
本文介绍了简单的c ++指针铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释这个问题:

Can someone explain this to me:

char* a;
unsigned char* b;

b = a;
// error: invalid conversion from ‘char*’ to ‘unsigned char*’

b = static_cast<unsigned char*>(a);
// error: invalid static_cast from type ‘char*’ to type ‘unsigned char*’

b = static_cast<unsigned char*>(static_cast<void*>(a));
// everything is fine

cast 2和3之间有什么区别?如果3的方法用于其他(更复杂的)类型,是否有任何陷阱?

What makes the difference between cast 2 and 3? And are there any pitfalls if the approach from 3 is used for other (more complex) types?


由于一些提到的坏设计等。 ..

[edit] As some mentioned bad design, etc...

这个简单的例子来自一个图像库,它给我指向图像数据的指针 char * 。显然图像强度总是正的,所以我需要解释为 unsigned char 数据。

This simple example comes from an image library which gives me the pointer to the image data as char*. Clearly image intensities are always positive so I need to interpret it as unsigned char data.

推荐答案

static_cast< void *> 消除类型检查的目的,因为你说现在它指向你不知道类型的东西。然后编译器必须信任你,当你在 void * 上说 static_cast< unsigned char *> / code>然后他会尝试以明确的方式做他的工作

static_cast<void*> annihilate the purpose of type checking as you say that now it points on "something you don't know the type of". Then the compiler have to trust you and when you say static_cast<unsigned char*> on your new void* then he'll just try to do his job as you ask explicitely.

c $ c> reinterpret_cast<> 如果你真的必须在这里使用转换(因为这是obvioulsy在这里显示一个设计问题)。

You'd better use reinterpret_cast<> if you really must use a cast here (as it's obvioulsy showing a design problem here).

这篇关于简单的c ++指针铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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