为什么我必须要重新解释指针指针? [英] Why do I Have to reinterpret_cast Pointer Pointers?

查看:115
本文介绍了为什么我必须要重新解释指针指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,此static_cast代码完全合法:

So this static_cast code is totally legal:

int n = 13;
void* pn = static_cast<void*>(&n);
void** ppn = &pn;

然而,必须将其制作为reinterpret_cast进行编译:

Yet this has to be made into a reinterpret_cast to compile:

int n = 13;
int* foo = &n;
void** bar = static_cast<void**>(&foo);

如果我不更改它,则会收到错误消息:

If I don't change it I get the error:

错误C2440:static_cast:无法从int **转换为void ** 注意:指向的类型无关.转换需要reinterpret_cast,C样式强制转换或函数样式强制转换

error C2440: static_cast: cannot convert from int ** to void ** note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

所以我认为问题是类型无关".但是我还是不明白,如果从int*转到void*没问题,怎么不能将它们与int**void**无关?

So I take it the issue is "the types are unrelated". Yet I still don't understand, if it's OK when going from an int* to void* how can they be unrelated as a int** and a void**?

推荐答案

intvoid毫无关系. int**void**也是一样,因此无法使用static_cast进行转换.

int is in no way related to void. The same goes for int** and void** and so they cannot be converted using static_cast.

void*特殊.尽管没有与void相关的类型,但任何数据指针类型(包括int*)都可以static_cast转换为void*(返回)(即使更进一步,转换为void*也不需要强制转换,因为它是隐式的). int*没有此属性,void**也没有,并且除了void*也没有其他任何指针.

void* however, is special. Any data pointer type (including int*) can be static_cast into void* and back, despite no type being related to void (even further, the conversion to void* doesn't need a cast, as it is implicit). int* doesn't have this property, nor does void** and nor does any other pointer besides void*.

已授予void*的其他自由带有附加的限制. void*不能被间接使用,也不能与指针算法一起使用.这些限制仅是可能的,因为永远不会存在void类型的对象.或者从相反的角度来看,由于这些限制,void的对象不能存在.

The additional freedoms that have been granted to void* come with additional restrictions. void* cannot be indirected, nor can it be used with pointer arithmetic. These restrictions are only possible because there can never be an object of type void. Or from opposite point of view, objects of void cannot exist because of these restrictions.

void**这些自由,因为不能给予相同的限制.不能赋予这些限制,因为void*对象确实存在并且它们必须存在.如果我们不能间接或迭代void**,那么就不能使用void*数组.

void** cannot be given those freedoms, because it cannot be given the same restrictions. It cannot be given those restrictions because void* objects do exist and they need to exist. If we couldn't indirect or iterate void**, then we couldn't use arrays of void* for example.

这篇关于为什么我必须要重新解释指针指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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