查看 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/