如何在 C++ 中将指针转换/转换为引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10172735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:42:48  来源:igfitidea点击:

How to cast/convert pointer to reference in C++

c++pointerscastingreferencetype-conversion

提问by Dewsworld

How can I pass a pointer (Object *ob) to a function which prototype is void foo(Object &)?

如何将指针 ( Object *ob)传递给原型是的函数void foo(Object &)

回答by David Heffernan

Call it like this:

像这样调用它:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

请注意,正如您的问题标题中所建议的那样,此处没有进行转换。我们所做的只是取消引用指向对象的指针,然后将其传递给函数。

回答by Roee Gavirel

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

您不需要强制转换它,因为它是相同的 Object 类型,您只需要取消引用它。