所以我有两个字符数组

unsigned char v[2];

我想将v [0]的值显示为从0到255的数字,但是
cout << v[0] << endl; //prints some garbage

cout << (void*)v[0] << endl; //prints the right thing but in hex

所以我尝试了
cout << (int)v[0] << endl;

或者
printf("%d\n", v[0]);

这正好显示了我想要的内容,但我一点都不喜欢。另外我根本不明白的是为什么这不起作用:
cout << reinterpret_cast<int>(v[0]) << endl; //compiler error

最佳答案

(用外行术语)reinterpret_cast用于以实现定义的方式将对象的位解释为另一种类型。您不想要这样:您想要一个转换(从char到int)。请改用static_cast

(5.2.10列出了reinterpret_cast的所有可能用法;这不是其中之一。)

关于c++ - 为什么C样式强制转换有效,但reinterpret_cast无效?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12021335/

10-11 22:10