指针&参考 [英] Pointers & References
本文介绍了指针&参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好。
为什么在以下程序中,输出为2.5?
浮动x = 2.5;
float&ref = x;
float * p1;
p1 =&ref + 2;
++(* p1);
cout<< ref;
Hello everyone.
why in below program, output is 2.5?
float x = 2.5;
float &ref = x;
float *p1;
p1 = &ref + 2;
++(*p1);
cout << ref;
推荐答案
这是因为你从未修改ref
引用的值,所以,最后,您可以看到初始化ref
时分配的值。
您可能对您使用p1
进行操作感到困惑。是的,如果它是用p1 =& ref
初始化的,那么你将有ref == 3.5;
但是,一些奇怪的原因,你在指针上添加了2,也就是说,指向x
后面的内存区域(顺便说一下,这是非常不安全的)。
SA
This is because you never modified the value referenced byref
, so, at the end, you see the value you assigned by the moment when you initializedref
.
You probably have been confused by your manipulations withp1
. Yes, if it was initialized withp1 = &ref
, you would haveref == 3.5;
but, by some weird reason, you added 2 to the pointer, that is, pointed the memory area behindx
(which is, by the way, is quite unsafe).
SA
这篇关于指针&参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文