2014-03-19 31 views
1

我正嘗試從我的類函數中多個位置的文件中讀取。因此,我認爲這是明智的宣佈對象在頭文件(私人),但我做了它後,它不工作了無法獲取作爲我的類中的成員聲明的ifstream對象

我沒有使用搜索功能,發現有關複製構造函數可能是問題,但我真的不知道他們做了什麼,以及爲什麼我需要改變某些事情對他們(如果是這樣,即使在我的代碼的情況下)

command.h:

class command 
{ 
public: 

command(); 
~command(); 
void printCommands() const; 

private: 
std::ifstream file; 

} 

Command.cpp

command::command(){ 
file.open("commands.txt"); 
} 
command::~command() 
{ 
file.close(); 
} 
void command::printCommands() const 
{ 
int i = 0; 

std::string line; 
std::cout <<"Command list:\n\n"; 

while (getline(file,line)) 
{ 
    std::cout << line <<endl<<endl; 
} 
} 

這僅僅是一個代碼的一部分,但basicly我在getline函數

我得到這個錯誤得到errror

error C2665: 'std::getline' : none of the 2 overloads could convert all the argument types 
std::basic_istream<_Elem,_Traits> &std::getline<char,std::char_traits<char>,std::allocator<_Ty>>  (std::basic_istream<_Elem,_Traits> &&,std::basic_string<_Elem,_Traits,_Alloc> &) 

EDIT1:

我沒有忘記,如果我確實移動了

std::ifstream file; 

進入cpp函數(我使用getline函數)它工作沒有問題,但它不應該與私人的declarition工作?

回答

2

您的command::printCommands()被聲明爲const。由於file是成員,因此您試圖通過const ifstream&作爲非常量std::istream&參數(由std::getline收到)。

轉換在調用時丟失const限定符(因此編譯失敗,出現錯誤)。

要修復,請從command::printCommands()中刪除const限定符。

+0

或標記'文件'爲'可變' –

+0

@AlexanderTobiasHeinrich,這將工作(但我認爲這是錯誤的語義)。我將mutable看作不屬於對象值的東西(例如,爲提高效率而緩存在對象中的複雜結果)。由於代碼修改了文件對象狀態,我認爲將文件標記爲可變(即使修復了編譯器錯誤)是不正確的。 – utnapistim

+0

有人可能會爭辯說,如果成員函數改變其對象的內部狀態,那麼將成員函數標記爲'const'也是錯誤的...... –

1
void command::printCommands() const 

該行聲明printCommands()是一個const函數。也就是說,不會更改command對象。從輸入流讀取是一個變化,所以如果輸入流是command的一部分,那麼從它讀取必然會改變command

我不知道你的程序,所以我不能說是否之後是一個好主意或沒有,但應該讓錯誤消失:聲明file作爲可變成員:

mutable std::ifstream file;