增加参考变量的运算符

ren*_*kar 8 c++

为什么预增量工作但后增量不在参考变量上?

#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;
} 
Run Code Online (Sandbox Code Playgroud)

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

[Error]从'int'类型的右值初始化'int&'类型的非const引用无效

Nat*_*ica 8

你打电话的时候

swap (a++,b++)
Run Code Online (Sandbox Code Playgroud)

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