使用const使參數可以轉換

 請看下面的代碼

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章