【发布时间】:2014-01-15 16:25:55
【问题描述】:
int main() {
int x=10;
int *p=&x;
int &y =*p;
cout<< x << endl << &x <<endl;
cout<< *p << endl << p <<endl;
cout<< y << endl << &y <<endl;
p++;
*p = 20;
cout<< x << endl << &x <<endl;
cout<< *p << endl << p <<endl;
cout<< y <<endl<< &y <<endl;
return 0;
}
以上是最能解释我的问题的代码。通常,变量引用 (&) 获取变量的地址并开始引用该变量。我试过通过指针做同样的事情。我定义了一个变量,指针 p 指向 x,引用变量 y 指向 *p。这是否意味着 y 现在指的是同一个变量 x ? 下一步,我停止通过 *p 指向 x,现在引用变量 y 会发生什么?它会持有什么。 在上面的代码中,cout
谁能帮忙解释一下这里的行为。
【问题讨论】:
-
@Pilot no,
int *const y = p,访问语法不同 -
@Andrey yes....ref 是 const 指针
-
Normally, a variable reference (&) takes the address of a variable and starts referring to the same不要以这种方式开始考虑引用。 -
@Pilot:不要以这种方式开始考虑引用。如果您已经开始,停止。
-
@LightnessRacesinOrbit 你能解释一下已经开始是什么意思,停止