Passing references to pointers in C++(在 C++ 中传递对指针的引用)
问题描述
据我所知,没有理由不允许我在 C++ 中传递对指针的引用.但是,我这样做的尝试失败了,我不知道为什么.
As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.
这就是我正在做的:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(&s);
// ...
}
我收到此错误:
无法将参数 1 从 'std::string *' 转换为 'std::string *&'
cannot convert parameter 1 from 'std::string *' to 'std::string *&'
推荐答案
您的函数需要对调用范围内的实际字符串指针的引用,而不是对匿名字符串指针的引用.因此:
Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
string s;
string* _s = &s;
myfunc(_s);
应该编译就好了.
然而,这仅在您打算修改传递给函数的指针时才有用.如果您打算修改字符串本身,您应该按照 Sake 的建议使用对字符串的引用.考虑到这一点,编译器为什么抱怨你的原始代码应该更明显了.在您的代码中,指针是动态"创建的,修改该指针不会产生任何后果,这不是预期的.引用(相对于指针)的想法是引用始终指向实际对象.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.
这篇关于在 C++ 中传递对指针的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中传递对指针的引用


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01