2016-05-11 29 views
0

在主:發送一個字符串變量作爲參數來打開一個文件

void HandleAction(const RandomWriter & rw, string choice) 
{ 
    if(choice == "P") 
    { 
    string fileInput; 
    cout << "Change input file: " << endl; 
    cin >> fileInput; 
    rw.SetFilename(fileInput); 
    } 
} 

在RandomWriter類:

void RandomWriter::SetFilename(string filename) 
{ 
string text = GetFullFile(filename); 
if (text != "") 
{ 
    fullText = text; 
    this->filename = filename; 
} 

/

當我嘗試,爲什麼我得到這個錯誤將fileInput作爲參數傳遞給SetFileName?

在此先感謝你們!

||=== error: passing 'const RandomWriter' as 'this' argument of 'void RandomWriter::SetFilename(std::string)' discards qualifiers [-fpermissive]| 
+0

閱讀槽這裏的答案http://stackoverflow.com/questions/2382834/discards-qualifiers-error –

+0

如果你想檢查一個'std :: string'對象是否爲空,那麼['empty '](http://en.cppreference.com/w/cpp/string/basic_string/empty)成員函數。 –

回答

1

HandleAction功能你說的那個rw是一個不斷RandomWriter對象的引用。然後您嘗試調用rw對象上的成員函數,該對象試圖通過修改該常量對象。這當然是不允許的,你不能修改常量對象。

所以簡單的解決方法是刪除參數規範的const部分:

void HandleAction(RandomWriter & rw, string choice) { ... } 
//    ^^^^^^^^^^^^^^^^^ 
//   Note: No longer constant 

在相關的註釋,你應該使用常量對象的參考雖然,沒有需要隨時複製它們。

+0

感謝您的回覆!有用 – Ares

0

RandomWriter參數rw在您HandleAction()方法中聲明const,因而不變,無法通過你的電話被更改爲SetFilename()

相關問題