首页 > 解决方案 > 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 语句实现引用分配,但如果我不能使用它怎么办?

标签: c++reference

解决方案


使用一个功能:

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在问题中使用它,所以我保持这样。


推荐阅读