我正嘗試從我的類函數中多個位置的文件中讀取。因此,我認爲這是明智的宣佈對象在頭文件(私人),但我做了它後,它不工作了無法獲取作爲我的類中的成員聲明的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工作?
或標記'文件'爲'可變' –
@AlexanderTobiasHeinrich,這將工作(但我認爲這是錯誤的語義)。我將mutable看作不屬於對象值的東西(例如,爲提高效率而緩存在對象中的複雜結果)。由於代碼修改了文件對象狀態,我認爲將文件標記爲可變(即使修復了編譯器錯誤)是不正確的。 – utnapistim
有人可能會爭辯說,如果成員函數改變其對象的內部狀態,那麼將成員函數標記爲'const'也是錯誤的...... –