为什么 getline 的字符串版本是非成员函数?

发布于 2024-10-07 14:05:22 字数 262 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

听不够的曲调 2024-10-14 14:05:22

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 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*.

我的奇迹 2024-10-14 14:05:22

因为 iostream 类的实现不应该依赖于字符串。

Because the implementation of the iostream classes should not depend on strings.

庆幸我还是我 2024-10-14 14:05:22

流库的问题在于它设计得不好。特别是成员函数 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文