如何从引用获取指针? [英] How to get a pointer from a reference?

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

问题描述

似乎有许多相关的问题谈论指针和引用,但我找不到我想知道的。基本上,一个对象通过引用传递:

There seems to be many relavent questions talking about pointer vs. reference, but I couldn't find what I want to know. Basically, an object is passed in by a reference:

funcA(MyObject &objRef) { ... }

在函数中,我可以获得一个指向该对象的指针,而不是引用?如果我将参考 objRef 视为 MyObject 的别名,将& objRef 实际上给了我一个指针MyObject?它似乎不可能。我很困惑。

Within the function, can I get a pointer to that object instead of the reference? If I treat the reference objRef as an alias to the MyObject, would &objRef actually give me a pointer to the MyObject? It doesn't seem likely. I am confused.

编辑:仔细检查, objRef 确实给我回到我需要的对象的指针 - 大多数人给了我正确的信息/答案,非常感谢。

Upon closer examination, objRef does give me back the pointer to object that I need - Most of you gave me correct info/answer, many thanks. I went along the answer that seems to be most illustrative in this case.

推荐答案

是的,将运算符的地址应用于引用与获取原始对象的地址相同。

Yes, applying the address-of operator to the reference is the same as taking the address of the original object.

#include <iostream>

struct foo {};

void bar( const foo& obj )
{
  std::cout << &obj << std::endl;
}

int main()
{
  foo obj;
  std::cout << &obj << std::endl;
  bar( obj );

  return 0;
}

结果:

0x22ff1f
0x22ff1f

这篇关于如何从引用获取指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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