请看下面的代码
#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&是一个更好的代码风格,如下:
{
cout << str << endl;
}
int main()
{
foo("This will compile successfully!");
return 0;
}
此段代码可以顺利编译,foo可以接受一个临时的变量,达到了参数转换的目的。