Reputation: 618
i am trying to read from a file in multiple places in my class functions. Therefor i thought it would be smart to declare the object in the headerfile(in private) but after i did that it does not work anymore
I did use the search function and found something about copy constructors might be the problem but i don't really know what they do and why i need to change something about them(if that is even the case in my code)
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;
}
}
This is just a part of the code but basicly i get an errror at the getline function
i get this error
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:
I did forget, if i do move the
std::ifstream file;
into the cpp functions (where i use the getline functions) it works without a problem, but shouldn't it work with the declarition in private?
Upvotes: 1
Views: 361
Reputation: 88155
void command::printCommands() const
That line declares printCommands()
to be a const function. I.e., one that does not change the command
object. Reading from an input stream is a change, so if the input stream is part of the command
then reading from it necessarily changes the command
.
I don't know your program so I can't say whether the following is a good idea or not, but it should make the error go away: declare file
as a mutable member:
mutable std::ifstream file;
Upvotes: 1
Reputation: 27365
Your command::printCommands()
is declared const. Since file
is a member, you are trying to pass a const ifstream&
as a non-const std::istream&
parameter (received by std::getline
).
The conversion looses the const
qualifier on call (so compilation fails with the error you got).
To fix, remove the const qualifier from command::printCommands()
.
Upvotes: 2