假设我希望 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/