gpt4 book ai didi

c++ - 调用指针和引用方法

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:05 25 4
gpt4 key购买 nike

如果有一个方法以指针为参数,另一个重载方法以引用为参数,我该如何具体调用一个或另一个?

例如。

int foo (int const& lippman) { \do something }
int foo (int && lippman) { \do something else }

--所以现在当我想调用一个或另一个时,我该如何调用它/编译器如何区分两者(显然是通过参数,但如何?)

谢谢

最佳答案

int foo (X const&);
int foo (X&&);

这些不是指针。第一个是 const 引用,第二个是 r-value 引用。区分它们:

X x{};
foo( x ); // call the first version
foo( std::move(x) ); // call the second version (also with temporary: foo( X{} ); )

注意:第三个重载(通过指针)是:

int foo(X* x); // or "const X* x" or "const X* const x"

调用与上面相同的 x 实例:

foo(&x); // get address of x and pass to "foo"

关于c++ - 调用指针和引用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com