c++ - 关于ostream类和运算符<<的误解

标签 c++ iostream

查看 ostream::operator << 后C++ 引用,

我注意到以下声明:

ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);
ostream& operator<< (streambuf* sb );
ostream& operator<< (ostream& (*pf)(ostream&));
ostream& operator<< (ios& (*pf)(ios&));
ostream& operator<< (ios_base& (*pf)(ios_base&));

但后来发现还有如下声明:

ostream& operator<< (ostream& os, char c);
ostream& operator<< (ostream& os, signed char c);
ostream& operator<< (ostream& os, unsigned char c);
ostream& operator<< (ostream& os, const char* s);
ostream& operator<< (ostream& os, const signed char* s);
ostream& operator<< (ostream& os, const unsigned char* s);

为什么字符/字符串输出运算符不是成员函数?

最佳答案

第一组运算符是流类的成员。

大多数运算符重载,如第二组中的重载,都不是。


至于原因,这很可能只是一个历史事故。内置类型的运算符可以添加到流类中,显然它们是(早在 C++ 标准化之前)。该标准仅记录此处的现有实践。

用户定义类型的运算符显然不能添加到流类中,因此它们被实现为自由函数。

回想起来,让所有运算符成为自由函数会更加一致,但这可能会破坏一些旧程序。

关于c++ - 关于ostream类和运算符<<的误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16015051/

相关文章:

c++ - MFC CString 是宽字符字符串吗

java - 将 C++ long 类型转换为 JNI jlong

c++ - 如何正确重载 ostream 的 << 运算符?

c++ - 如何在 C++ 中对齐用户输入(不使用 iomanip)

c++ - 用于集群的 C/C++ 机器学习库

c++ - 索引的顺序影响 OPENGL 中的立方体结构

c++ - 在 C++ 中显示带有填充和固定位数的数字

c++ - 如何在不复制和保留 std::string 对象的情况下获得 C++ std::string char 数据的所有权?

c++ - 如何在一行中用户输入c++中的数组元素

c++ - Typedef 数组混淆