更改引用后增加值不会增加两个值
Increasing value after changing a references does not increase both values
在 C++ 中更改引用的目标并增加初始值时,为什么 a
和 b
在以下示例中不相同:
输出: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;
}
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;
}
引用不跟踪 b
,因此 b
不会将其值更改为 11。它类似于:
int* ref = &a;
*ref = b;
减轻这种可能的混淆,即引用可以设置为在初始化后跟踪另一个变量(他们不能!)的一种可能方法是使用花括号初始化器来初始化引用.所以
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
changing the target of a reference
不可以,引用不能在初始化后重新绑定。然后
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
在 C++ 中更改引用的目标并增加初始值时,为什么 a
和 b
在以下示例中不相同:
输出: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;
}
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;
}
引用不跟踪 b
,因此 b
不会将其值更改为 11。它类似于:
int* ref = &a;
*ref = b;
减轻这种可能的混淆,即引用可以设置为在初始化后跟踪另一个变量(他们不能!)的一种可能方法是使用花括号初始化器来初始化引用.所以
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
changing the target of a reference
不可以,引用不能在初始化后重新绑定。然后
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