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

3

到目前为止,我已经尝试了这个方法,但是在下面的代码中仍然出现错误:

#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 functionint 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
为什么这个被踩了?问题很清楚,发布者展示了代码。而且这是一个可以回答的实际编程问题。 - hetepeperfan
@hetepeperfan:实际上,问题不是很清楚。标题问如何做一件事(将const unsigned short转换为unsigned short),但在代码中,他试图做一些完全不同的事情(将const unsigned short (*)[2]转换为unsigned short*)。这并不意味着它应该被投票否决,这是一个诚实的错误,但它绝对需要一些澄清。 - Benjamin Lindley
2个回答

2

首先,您并不是返回一个unsigned short*,而是返回一个unsigned short (*) [2],即指向包含两个unsigned short的数组的指针。这可能不是您想要的。您的函数签名应该是:

unichar const* ret();

(C风格的数组在类型系统中本质上是有缺陷的,并且代表了一种特殊情况。)或者,您可能想返回一个引用:

unimap_t const& ret();

这应该转换为unsigned short const*


0
ret()函数更改为返回指向x的指针:
const unimap_t *ret()
{
    return &x; 
}

并添加一些reinterpret_cast:

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

1
我认为你的函数返回类型应该是 unichar const*。如果你需要使用 reinterpret_cast,那么你的代码可能存在问题。 - James Kanze
如果你使用reinterpret_cast从指向数组的指针转换为指向其第一个元素的指针,那么肯定是在做错事情。解引用后跟随数组到指针的衰减可以实现相同的效果。 - Steve Jessop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接