[英]How to convert const unsigned short to unsigned short?
So far I have tried this but I am still getting an error in the code below: 到目前为止,我已经尝试过这个,但我仍然在下面的代码中收到错误:
#include<iostream>
typedef unsigned short unichar;
typedef const unichar unimap_t[2];
unimap_t x = {0x0004,0x00ff};
const unimap_t * ret()
{
return x;
}
int main()
{
unsigned short* pX2 = const_cast < unsigned short* > (ret());
std::cout <<pX2[1];
return 0;
}
I am getting the following error. 我收到以下错误。
a.cpp: In function ‘int main()’:
sa.cpp:22:60: error: invalid const_cast from type ‘const unichar (*)[2]
{aka const short unsigned int (*)[2]}’ to type ‘short unsigned int*’`
First, you're not returning a unsigned short*
, but an unsigned short (*)[2]
, a pointer to an array of 2 unsigned short
. 首先,你没有返回
unsigned short*
,而是unsigned short (*)[2]
,指向2 unsigned short
数组的指针。 This is probably not what you want; 这可能不是你想要的; the signature of your function should probably be:
你的函数的签名应该是:
unichar const* ret();
(C style arrays are fundamentally broken, and represent a special case in the type system.) Alternatively, you might want to return a reference: (C样式数组从根本上被打破,并且代表了类型系统中的特殊情况。)或者,您可能希望返回一个引用:
unimap_t const& ret();
This should convert to unsigned short const*
. 这应该转换为
unsigned short const*
。
Change the ret()
function to return a pointer to x
: 更改
ret()
函数以返回指向x
的指针:
const unimap_t *ret()
{
return &x;
}
and add some reinterpret cast: 并添加一些重新解释强制转换:
int main() {
unsigned short* pX2 = const_cast < unsigned short* >(
reinterpret_cast<const unsigned short*>(ret())
);
std::cout <<pX2[1];
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.