Reputation: 2882
After reading Jerry Coffin's answer on this question I copy-pasted his code into my editor, and after some minor edits it compiled and run like it should.
Here is the code after the changes:
#include <iostream>
#include <string>
#include <istream>
#include <fstream>
class non_blank {
private:
std::string data_;
friend std::istream& operator>> (std::istream &is, non_blank &n) {
std::getline(is, n.data_);
if (n.data_.length() == 0) {
is.setstate(std::ios::failbit);
}
return is;
}
public:
operator std::string() const {
return data_;
}
};
int main(int, char *[]) {
non_blank line;
std::ifstream ifs("teste.txt");
while(ifs >> line) {
//std::cout << line; <----- error
std::string s = line;
std::cout << s << std::endl;
}
return 0;
}
I've got an error when trying to use a non_blank variable in a std::cout <<...
expression. Shouldn't I be able to use a variable of the type non_blank anywhere I would use a std::string? Isn't it the purpose of the cast/conversion operator?? answer
Why can't I access the private variable string::data_
directly in the definition of the operator >>
?
Here is the error I got:
..\main.cpp: In function `std::istream& operator>>(std::istream&, non_blank&)':
..\main.cpp:21: error: invalid use of non-static data member `non_blank::data_'
..\main.cpp:26: error: from this location
Upvotes: 2
Views: 2886
Reputation: 249582
Shouldn't I be able to use a variable of the type non_blank anywhere I would use a std::string? Isn't it the porpuse of the cast operator?
Not quite. If the compiler sees you doing something that it knows requires a std::string, it can call your conversion operator to get one. But in the case of the ostream operator <<, it doesn't have a single specific function to call, but rather quite a lot of them, all different and none matching precisely the actual type you mean to print. So it lists a whole bunch of candidates, none of which is a strong enough match. You need to define an ostream operator << for your type in order to make it print as it should.
As for your operator >>, you should make it not be a member of your class. Declare it as a friend within the class declaration if you must, but write the function itself outside.
Upvotes: 1