指针&参考 [英] Pointers & References

查看:55
本文介绍了指针&参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。

为什么在以下程序中,输出为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 by ref, so, at the end, you see the value you assigned by the moment when you initialized ref.

You probably have been confused by your manipulations with p1. Yes, if it was initialized with p1 = &ref, you would have ref == 3.5; but, by some weird reason, you added 2 to the pointer, that is, pointed the memory area behind x (which is, by the way, is quite unsafe).

SA


这篇关于指针&amp;参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆