为什么我不能使用 static_cast<int&> 将整数引用参数传递给 C++ 中的函数?

Why can't I use static_cast<int&> to pass an integer reference parameter to a function in C++?

本文关键字:参数传递 整数 引用 C++ 函数 int 不能 static 为什么 lt cast      更新时间:2023-10-16

我在C++程序中有一个枚举参数,我需要使用通过参数返回值的函数来获得它。我一开始把它声明为int,但在代码审查时被要求把它键入enum(ControlSource(。我这样做了,但它破坏了Get((函数——我注意到C样式转换为int&解决了问题,但当我第一次尝试使用static_cast<>修复它时它没有编译。

为什么会这样,为什么当eTimeSource是int时,通过引用传递整数根本不需要强制转换?

//GetCuePropertyValue signature is (int cueId, int propertyId, int& value);
ControlSource eTimeSource = ControlSource::NoSource;
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, static_cast<int&>(eTimeSource)); //This doesn't work.
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, (int&)(eTimeSource)); //This does work.
int nTimeSource = 0;
pPlayback->GetCuePropertyValue(blah, blah, nTimeSource); //Works, but no (int&) needed... why?

当您将变量转换为不同类型的值时,您将获得一个临时值,该值不能绑定到非常量引用:修改临时值毫无意义。

如果您只需要读取值,则可以使用常量引用:

static_cast<int const &>(eTimeSource)

但你也可以创建一个实际的价值,而不是一个参考:

static_cast<int>(eTimeSource)
static_cast<int&>((eTimeSource))); //This doesn't work.

是的,它不起作用,因为eTimeSource不是int,所以你不能将int&绑定到它

(int&)((eTimeSource))); //This does work.

错了,这也不起作用,只是看起来起作用。C风格的转换对编译器撒谎,并说"即使这不合法,也要把它变成这种类型"。仅仅因为某个东西可以编译并不意味着它可以工作。

为什么当eTimeSourceint时,通过引用传递整数根本不需要强制转换?

因为可以将int&绑定到int,但不能绑定到其他类型,而eTimeSource是不同的类型。CCD_ 9是对CCD_。如果你能将它绑定到另一个类型,它就不会引用int,是吗?

如果代码评审员说要将变量更改为枚举类型,那么他们可能也意味着要将函数参数更改为ControlSource&