简体   繁体   中英

How to cast a variable member to pass it as reference argument of a function

When I try to compile some code very similar to this one with VC++2015 I get a:

C2664 cannot convert parameter number 1 from 'unsigned int' to 'short &'

class Foo
{
public:
    unsigned int A;
    unsigned int B;
}

void foo(short& a)
{
    a++;
}

void main()
{
    Foo f;
    foo(f.A);
}

What is the correct way to cast it?

It is not possible to do this with a cast because unsigned int cannot be aliased as short . To call this foo without changing it, the code would be:

if ( f.A > SHRT_MAX )
    throw std::runtime_error("existing value out of range for short");

short sh = f.A;
foo(sh);
f.A = sh;

You may want to check sh >= 0 before reassigning it to fA ; and foo should guard against integer overflow.

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