Ale*_*lex 120 c++ pointers reference
据我所知,没有理由不允许我在C++中传递对指针的引用.但是,我这样做的尝试失败了,我不知道为什么.
这就是我正在做的事情:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(&s);
// ...
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
无法将参数1从'std :: string*'转换为'std :: string*&'
Chr*_*ris 118
您的函数需要引用调用范围中的实际字符串指针,而不是匿名字符串指针.从而:
string s;
string* _s = &s;
myfunc(_s);
Run Code Online (Sandbox Code Playgroud)
应该编译得很好.
但是,这仅在您打算修改传递给函数的指针时才有用.如果您打算修改字符串本身,您应该使用Sake建议的字符串引用.考虑到这一点,编译器抱怨原始代码的原因应该更加明显.在你的代码中,指针是"动态"创建的,修改指针没有任何后果,这不是预期的.引用(与指针相对)的想法是引用始终指向实际对象.
Mic*_*urr 84
问题是你试图将临时绑定到引用,除非引用,否则C++不允许const.
所以您可以执行以下任一操作之一:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
void myfunc2(string* const& val)
{
// Do stuff to the string pointer
}
int main()
// sometime later
{
// ...
string s;
string* ps = &s;
myfunc( ps); // OK because ps is not a temporary
myfunc2( &s); // OK because the parameter is a const&
// ...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
aJ.*_*aJ. 10
将其更改为:
std::string s;
std::string* pS = &s;
myfunc(pS);
Run Code Online (Sandbox Code Playgroud)
编辑:
这被调用ref-to-pointer,你不能传递临时地址作为函数的引用.(除非是const reference).
虽然,我已经显示std::string* pS = &s;(指向局部变量的指针),但它的典型用法是:当你希望被调用者改变指针本身时,而不是指向它的对象.例如,一个分配内存并分配它分配给其参数的内存块地址的函数必须引用指针或指针指针:
void myfunc(string*& val)
{
//val is valid even after function call
val = new std::string("Test");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
139139 次 |
| 最近记录: |