如何强制转换变量成员以将其作为函数的引用参数传递

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

本文关键字:函数 参数传递 引用 转换 何强制 变量 成员      更新时间:2023-10-16

当我尝试使用 VC++2015 编译一些与此代码非常相似的代码时,我得到:

C2664 无法将参数编号 1 从"无符号 int"转换为"短 &"

class Foo
{
public:
    unsigned int A;
    unsigned int B;
}
void foo(short& a)
{
    a++;
}
void main()
{
    Foo f;
    foo(f.A);
}

正确的投射方法是什么?

无法

使用强制转换执行此操作,因为unsigned int不能别名为 short 。要调用此foo而不更改它,代码将是:

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;

在将sh >= 0重新分配给f.A之前,您可能需要检查它;并且foo应该防止整数溢出。