将引用转换为 C++ 中的指针表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19032461/
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
convert reference to pointer representation in C++
提问by Mark
Is there a way to "convert" a reference to pointer in c++? In example below, func2
has already defined prototype and I can't change it, but func
is my API, and I'd like to either pass both parameters, or one (and second set to NULL) or neither (both set to NULL):
有没有办法在 C++ 中“转换”对指针的引用?在下面的示例中,func2
已经定义了原型并且我无法更改它,但它func
是我的 API,我想传递两个参数,或者传递一个(第二个设置为 NULL)或都不传递(都设置为 NULL):
void func2(some1 *p1, some2 *p2);
func(some1& obj, some2& obj2)
{
func2(..);
}
回答by Chen
func2(&obj, &obj2);
func2(&obj, &obj2);
Use reference parameters like normal variables.
像普通变量一样使用引用参数。
回答by Jonathan Wood
Just get the address of the object.
只需获取对象的地址即可。
some1 *p = &obj;
Or in your case:
或者在你的情况下:
func2(&obj, &obj2);
回答by Umer Farooq
func2(&obj, &obj2);
is what you should use.
是你应该使用的。
回答by Jarod42
In normal cases, you can simply use &
:
在正常情况下,您可以简单地使用&
:
void func(some1& obj, some2& obj2)
{
func2(&obj, &obj2);
}
but operator&
might be overloaded, so std::addressof
(since C++11) should be used for those cases:
但operator&
可能会重载,因此std::addressof
(自 C++11 起)应用于这些情况:
void func(some1& obj, some2& obj2)
{
func2(std::addressof(obj), std::addressof(obj2));
}
回答by Jarod42
For a clean design put all in a class (or use namespaces)
对于干净的设计,将所有内容放在一个类中(或使用命名空间)
class X {
private:
void func2(someA*, someB*);
public:
func(someA& a, someB& b) { func2(&a, &b); }
func(someA& a) { func2(&a, 0); }
func() { func2(0, 0); }
}