請看下面的代碼
#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可以接受一個臨時的變量,達到了參數轉換的目的。