c++ - 为什么我可以为字符串重载 istream 的 operator>>?

标签 c++ operator-overloading iostream

假设我希望 operator>>istream 中提取整行而不是空格分隔的单词。我很惊讶地看到这虽然很糟糕,但实际上有效:

#include <iostream>
#include <string>

namespace std {
  istream &operator>>(istream &is, string &str) {
    getline(is, str);
  }
}

int main() {
  std::string line;
  std::cin >> line;
  std::cout << "Read: '" << line << "'\n";
}

如果我在 stdin 中键入多个单词,它实际上会调用我的运算符并读取整行。

我希望 operator>> 的这个定义official one 冲突, 产生链接错误。为什么不呢?


编辑:我想也许真正的 operator>> 是一个模板,非模板函数优先,但这仍然有效:

namespace std {
  template<typename charT>
  basic_istream<charT> &operator>>(basic_istream<charT> &is, basic_string<charT> &s) {
    getline(is, s);
  }
}

最佳答案

碰巧可以工作,因为官方模板is less specific (还有其他模板参数)。

不过是Undefined Behaviour™ .您只被允许为您自己的类型提供标准库符号的重载。如果您遇到另一个将定义额外重载的标准库(它可能),它将停止工作并且您不知道为什么。

关于c++ - 为什么我可以为字符串重载 istream 的 operator>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21182036/

相关文章:

java - iostream 和 read/writeObject 调用的基础知识

c++ - QTableView 中选中的行,复制到 QClipboard

c++ - 覆盖类型数组的下标/运算符[]

c++ - 如何在字符串中添加整数?

c# - 是否可以在 Stream 参数中限制/要求某些功能?

c++ - 无法使用 cin.get() 读取两个字符串

c++ - 没有片段拒绝的帧缓冲区纹理透明度?

c++ - 'value type' 的初始化没有匹配的构造函数

c++ - 为什么预先声明 std::basic_string<T> 会破坏 boost::regex?

c++ - 重载乘法运算符