如何根据 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 */
Run Code Online (Sandbox Code Playgroud)
但是,以下示例也不起作用,因为必须立即将引用分配给对象。
int x = 1;
int y = 2;
int & smaller; /* error: requires an initializer */
if(x < y)
{
smaller = x;
}
else if (x > y)
{
smaller = y;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用三元 if 语句实现引用赋值,但如果我不能使用它怎么办?三元 if 仅适用于最简单的情况,但不适用于多个 else-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 */
}
Run Code Online (Sandbox Code Playgroud)
请注意,在您的情况下,我什至希望 foo 返回 a ,const int&因为修改标识为较小的值似乎很奇怪,但因为您没有使用它const在问题中没有使用它,所以我保持这样。
编辑:
对于 C++ 11 及更高版本,您可以使用随时调用的 lambda:
int main() {
int x = 1;
int y = 2;
int & smaller = [&]() -> int & {
if(x < y)
{
return x;
}
else if (x > y)
{
return y;
} else {
// what do you expect to happen here?
return x;
}
}(); /* should work now */
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3278 次 |
| 最近记录: |