简体   繁体   中英

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 . 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:

unimap_t const& ret();

This should convert to unsigned short const* .

Change the ret() function to return a pointer to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM