C++ 参考 - 我不清楚的地方
C++ references - something is unclear to me
请看下面代码:
int x = 7;
int *p = &x;
int &y = x;
x = 7;
*p = 7;
y = 7;
当x = 42;
x = 42;
*p = 42;
y = 42;
当y = 73;
x = 73;
*p = 73;
y = 73;
为什么 x = 73?
在很多方面,引用可以看作是 "alias",同一事物的另一个名称,因此 x
和 y
是 "the same thing, just different names"。使用 y
代替 x
显然没有多大意义,但是如果你有一个又长又复杂的东西,比如
person individual;
if (individual.scores.mathtest[testno] > 75 &&
individual.scores.mathtest[testno] <= 100)
{
individual.scores.mathtest[testno] = 80;
}
然后使用
int &score = individual.scores.mathtest[testno];
if (score > 75 && score <= 100)
{
score = 80;
}
会大大减少编写 - 并且更容易看出它在整个代码部分都是同一件事 - 而不是试图发现该语句中某处是否存在差异。
如果是您的示例,您可以将 *p
视为另一个别名。指针的属性与引用略有不同——例如,您可以更改指针实际指向的位置。我们可以添加:
int z = 8;
p = &z;
现在 *p
不再是 x
的别名,而是 z
的别名。如果我们有:
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
int *p = &a[0];
我们有 *p
作为数组中元素 a[0]
的别名,我们可以使用
p++;
从 a[0]
移动到 a[1]
。
请看下面代码:
int x = 7;
int *p = &x;
int &y = x;
x = 7;
*p = 7;
y = 7;
当x = 42;
x = 42;
*p = 42;
y = 42;
当y = 73;
x = 73;
*p = 73;
y = 73;
为什么 x = 73?
在很多方面,引用可以看作是 "alias",同一事物的另一个名称,因此 x
和 y
是 "the same thing, just different names"。使用 y
代替 x
显然没有多大意义,但是如果你有一个又长又复杂的东西,比如
person individual;
if (individual.scores.mathtest[testno] > 75 &&
individual.scores.mathtest[testno] <= 100)
{
individual.scores.mathtest[testno] = 80;
}
然后使用
int &score = individual.scores.mathtest[testno];
if (score > 75 && score <= 100)
{
score = 80;
}
会大大减少编写 - 并且更容易看出它在整个代码部分都是同一件事 - 而不是试图发现该语句中某处是否存在差异。
如果是您的示例,您可以将 *p
视为另一个别名。指针的属性与引用略有不同——例如,您可以更改指针实际指向的位置。我们可以添加:
int z = 8;
p = &z;
现在 *p
不再是 x
的别名,而是 z
的别名。如果我们有:
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
int *p = &a[0];
我们有 *p
作为数组中元素 a[0]
的别名,我们可以使用
p++;
从 a[0]
移动到 a[1]
。