为什么 getline 的字符串版本是非成员函数?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
istream& istream::getline(char* s, Streamsize n)
是流接口的一部分。istream& getline(istream& is, string& str)
是string
库中的扩展方法(就像istream &operator>> 一样) (istream&, string&)
)。选择这种设计可能是为了将 iostreams 与 string 解耦,因为 fstream::open() 也不采用 std: :string 参数,而是
const char*
。istream& istream::getline(char* s, streamsize n)
is part of the stream interface.istream& getline(istream& is, string& str)
is an extension method from thestring
library (just like theistream &operator>>(istream&, string&)
).This design was probably chosen in order to decouple iostreams from string, as
fstream::open()
also does not takestd::string
arguments but ratherconst char*
.因为 iostream 类的实现不应该依赖于字符串。
Because the implementation of the iostream classes should not depend on strings.
流库的问题在于它设计得不好。特别是成员函数
getline
根本不应该存在。自由函数getline
是正确的选择,它有几个优点:它不是成员函数,它是安全的,不在原始缓冲区上工作,并且不需要猜测。需要指出的是,成员函数和自由函数都是 istream 公共接口的一部分。
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 functiongetline
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.