Why is the string version of getline a non-member function?
The getline
function has a开发者_如何学编程 character version that is a member function, as well as a global version that takes strings. Why aren't they both member functions? The current way makes it seems as though there isn't a string version.
istream& istream::getline(char* s, streamsize n)
is part of the stream interface.
istream& getline(istream& is, string& str)
is an extension method from the string
library (just like the istream &operator>>(istream&, string&)
).
This design was probably chosen in order to decouple iostreams from string, as fstream::open()
also does not take std::string
arguments but rather const char*
.
Because the implementation of the iostream classes should not depend on strings.
The trouble with stream library is that it's not well designed. In particular the member function getline
shouldn't be there at all. The free function getline
is he right one to use, it has several advantages: it's not a member function, it's safe, not working on raw buffers, and requires no guesswork.
It needs to be mentioned that both member- and free functions are part of istream public interface.
精彩评论