-3

在c++中更改引用的目标,并增加初始值时,为什么在以下示例中不一样ab

输出:a = 11 / b = 10

using namespace std;

void SampleMethod(int& val)
{
    val++;
}

int main()
{
    int a = 5;
    int b = 10;

    int& ref = a;
    ref = b;

    SampleMethod(a);


    cout << "Result: " << endl << a << endl << b << endl;
    return 0;
}

这是一个工作示例:https ://www.mycompiler.io/view/FVGKtQr

4

2 回答 2

3
void SampleMethod(int& val)
{
    val++;
}

int main()
{
    int a = 5;
    int b = 10;

    int& ref = a; //ref bound to a and has a's value i.e. 5
    ref = b; // ref doesn't point to b now but just sets the value of a to 10

    SampleMethod(a); // a gets incremented inside the function and becomes 11


    cout << "Result: " << endl << a << endl << b << endl;
    return 0;
}

The reference doesn't track b, so b doesn't change it's value to 11. It's similar to something like:

int* ref = &a;
*ref = b;

One probable way to mitigate this possible confusion that references could be set to track another variable after being initialized (they can't!) is to use braced initializers for initializing references. So

int& ref{a}; //Initializes reference and binds it to a
ref = b; // Changes the value of the underlying object (a) not setting it to b
于 2021-05-08T06:31:31.817 回答
3

changing the target of a reference

No, references can't be rebound after initialization. Then

int& ref = a;     // bind ref to a, i.e. make ref an alias of a
ref = b;          // assign b to ref, as the effect the object bound by ref (i.e. a) is assigned from b with value 10

SampleMethod(a);  // a is incremented to 11, b is still 10
于 2021-05-08T06:32:43.863 回答