为什么我不能使用 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,但在代码审查时被要求把它键入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风格的转换对编译器撒谎,并说"即使这不合法,也要把它变成这种类型"。仅仅因为某个东西可以编译并不意味着它可以工作。
为什么当
eTimeSource
是int
时,通过引用传递整数根本不需要强制转换?
因为可以将int&
绑定到int
,但不能绑定到其他类型,而eTimeSource
是不同的类型。CCD_ 9是对CCD_。如果你能将它绑定到另一个类型,它就不会引用int
,是吗?
如果代码评审员说要将变量更改为枚举类型,那么他们可能也意味着要将函数参数更改为ControlSource&
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 将整数数组作为参数传递C++错误
- 将整数或类型作为模板参数传递?
- 在 C++ 中将整数数组作为参数传递
- 将指向函数的指针数组作为"int"参数传递是否可以将地址转换为整数?
- 将参数传递给方法时,初始化内联整数数组