如何将const unsigned short转换为unsigned short?

时间:2013-12-13 09:25:16

标签: c++

到目前为止,我已尝试过此操作,但我仍然在下面的代码中收到错误:

#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;
}

我收到以下错误。

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*’`

2 个答案:

答案 0 :(得分:2)

首先,你没有返回unsigned short*,而是返回 unsigned short (*)[2],指向2 unsigned short数组的指针。这可能不是你想要的;签名 你的功能应该是:

unichar const* ret();

(C样式数组从根本上被打破,并代表 类型系统中的特殊情况。)或者,您可以 想要返回一个参考:

unimap_t const& ret();

这应转换为unsigned short const*

答案 1 :(得分:0)

更改ret()函数以返回指向x

的指针
const unimap_t *ret()
{
    return &x; 
}

并添加一些重新解释演员:

int main() {
    unsigned short* pX2 = const_cast < unsigned short* >(
            reinterpret_cast<const unsigned short*>(ret()) 
            );  
    std::cout <<pX2[1]; 
    return 0;
}