【发布时间】:2012-08-14 19:40:16
【问题描述】:
所以我有一个两个字符数组
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
【问题讨论】:
-
使用
static_cast代替它应该可以工作 -
@BoPersson:我不会假设每个使用 C 风格转换的人都在错误地这样做。从
unsigned char到int的演员阵容定义完美。
标签: c++ c casting reinterpret-cast