参考指针(如果我没记错的话) [英] Pointer to Reference (if I am not wrong)

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

问题描述



Hi,

void incr(int* &f)
{
    f++;
}

int main ()
{

    int *i = 0;
    std::cout<<"i ="<<i;
    incr(i);
    std::cout<<"i ="<<i;

  return 0;
}



我对带下划线的代码 int *& f 感到惊讶.您能解释一下这行的含义吗?



I am surprised looking at underlined code, int* &f. Can you explain meaning of this line.

推荐答案

那不是指向引用的指针,而是指向指针的引用.
That''s not a pointer to a reference, that''s a reference to a pointer.


反之亦然:f是对指针的引用.您是否运行了您的示例?您可以肯定地看到,在对incr的调用中,我增加了4.这可能是要在此处证明的重点. f是对int指针的引用,因此它的行为类似于对int的指针.当您增加它时,其值将增加等于计算机上int大小的字节数-在32位系统上通常为4.

只有通过引用传递f,才有可能在根本上看不到对f的更改.如果您按in
的值传递它
The other way around: f is a reference to a pointer. Did you run your example? What you certainly saw is that i is incremented by 4 in the call to incr. That''s probably the point to be demonstrated here. f is a reference to a pointer to int, so it behaves like a pointer to int. When you increment it, its value will increase by the number of bytes that equals the size of an int on your computer - usually 4 on 32-bit systems.

Only by passing f by reference made it possible that the change to f is visible in main at all. If you pass it by value like in

void incr(int* f)
{
    f++;
}



f会增加,但main看不到变化,因为它永远不会回到那里.



f would be incremented, but main would not see the change, as it never would get back there.


这篇关于参考指针(如果我没记错的话)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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