c++ - c ++在if语句中分配引用变量
问题描述
如何根据 if 语句分配引用变量?
例如,以下示例不起作用,因为“smaller”在 if 语句之外没有范围。
int x = 1;
int y = 2;
if(x < y)
{
int & smaller = x;
}
else if (x > y)
{
int & smaller = y;
}
/* error: smaller undefined */
但是,以下示例也不起作用,因为必须立即将引用分配给对象。
int x = 1;
int y = 2;
int & smaller; /* error: requires an initializer */
if(x < y)
{
smaller = x;
}
else if (x > y)
{
smaller = y;
}
我可以使用三元 if 语句实现引用分配,但如果我不能使用它怎么办?
解决方案
使用一个功能:
int &foo(int &x, int &y) {
if(x < y)
{
return x;
}
else if (x > y)
{
return y;
} else {
// what do you expect to happen here?
return x;
}
}
int main() {
int x = 1;
int y = 2;
int & smaller = foo(x, y); /* should work now */
}
请注意,在您的情况下,我什至希望 foo 返回 aconst int&
因为修改标识为较小的值似乎很奇怪,但是由于您没有const
在问题中使用它,所以我保持这样。
推荐阅读
- angular - 如何更改 ng-fullcalendar 的宽度
- ansible - Ansible 角色依赖于另一个角色的特定任务
- azure-devops - VSTS/TFS 扩展 TFS getFields()
- python - 如何在python中从现有列表中创建一个列表,其中包含第一个列表中的所有元素但索引较少
- cassandra - Cassandra 数据建模 - 识别最佳行键
- c++ - 为什么 `std::unary_function` 仍然在 c++17 中编译?
- javascript - jquery中的id不起作用
- c++ - CurlPP 不会多次请求
- python - PyCharm 代码完成不适用于已安装的库
- python - python numpy.nanmean() 返回 Nan