【问题标题】:Increment operator on reference variable引用变量的增量运算符
【发布时间】:2023-04-01 18:52:02
【问题描述】:

为什么在引用变量上,前增量有效,而后增量无效?

#include <iostream>

void swap(int&, int&);

int main()
{
    int x=10, y=20;
    int &a=x, &b=y;
    swap(++a, ++b);  //swap (a++,b++) is not allowed.
    printf("%d %d ", a, b);
    return 0;
}

void swap(int& x, int& y)
{
    x+=2;
    y+=3;
} 

为什么swap(++a, ++b) 允许但swap(a++, b++) 说:

[错误] 从“int”类型的右值初始化“int&”类型的非常量引用无效

【问题讨论】:

  • 为简单起见,请注意,如果您尝试直接使用mainxy,则会出现相同的行为。引用 ab 只会使问题看起来比实际更复杂。

标签: c++


【解决方案1】:

当你打电话时

swap (a++,b++)

a++b++ 给你一个临时对象,因为后递增返回以前的值。由于swap() 通过引用获取其参数,因此它们无法绑定到这些临时值。使用++a++b 工作,因为我们首先递增ab,然后将其传递给交换,因此没有临时性。

【讨论】:

    【解决方案2】:

    ++a 返回一个左值,但 a++ 返回一个右值。您需要将左值传递给 swap() 函数。

    关于左值和右值的相关帖子:postfix (prefix) increment, L-value and R-value (in C and C++)

    【讨论】:

      【解决方案3】:

      函数std::swap 必须交换两个变量的值,也就是左值引用。表达式x++ 不是变量,而是值或右值。右值不能绑定到左值引用。

      右值和左值的区别可以这样解释:

      int p;
      /* p is left value, 3 is right value, ok */
      p = 3;
      

      但以下内容无效:

      /* not ok, 3 is right value */
      3 = p;
      

      您发送给std::swap 的是两个数字值。

      【讨论】:

        【解决方案4】:

        传递左值/变量:

        int x = 5, y = 9;
        swap(x, y); // allowed bcos x and y are l-values / variables
        

        预增(也称为预减):

        int x = 5, y = 9;
        swap(++x, ++y); // allowed bcos ++x and ++y are l-values
        

        传递右值/值:

        swap(5, 9); // NOT allowed bcos 5 and 9 are values (NOT variables)
        

        后增量(也是后减量):

        int x = 5, y = 9;
        swap(x++, y++); // NOT allowed bcos x++ and y++ are r-values
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-19
          • 2016-10-14
          • 2011-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-18
          相关资源
          最近更新 更多