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

Gar*_*eth 9 c++ pass-by-reference static-cast

我在C++程序中有一个枚举参数,我需要使用一个通过参数返回值的函数来获取该参数.我首先将其声明为int,但在代码审查时要求将其键入为枚举(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?
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 8

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

如果您只需要读取值,则常量引用应该没问题:

static_cast<int const &>(eTimeSource)
Run Code Online (Sandbox Code Playgroud)

但您也可以创建一个实际值,而不是引用:

static_cast<int>(eTimeSource)
Run Code Online (Sandbox Code Playgroud)