请看下面的代码
#include <iostream>
#include <string>
using namespace std;
void foo(string& str)
...{
cout << str << endl;
}
int main()
...{
foo("This can't compile successfully!");
return 0;
}这将无法编译通过。因为在常量字符串参数与string之间存在转换,而foo的参数要求的是一个引用参数。事实上,我们发现,foo并不需要对参数str进行修改,因此使用const string&是一个更好的代码风格,如下:
void foo(const string& str)
...{
cout << str << endl;
}
int main()
...{
foo("This will compile successfully!");
return 0;
}此段代码可以顺利编译,foo可以接受一个临时的变量,达到了参数转换的目的。
C++字符串引用传参
本文探讨了C++中字符串引用作为函数参数时的注意事项,特别是对于常量字符串的处理方式,并提供了一种可行的解决方案。
2186

被折叠的 条评论
为什么被折叠?



