关于ostream类和运算符<< [英] Misunderstanding about ostream class and operator <<

查看:122
本文介绍了关于ostream类和运算符<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 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&));

但我发现还有以下声明:

But then I found out that there are also the following declarations:

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);

为什么char / string输出操作符不是成员函数?

Why are the char/string output operators not member functions?

推荐答案

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

The first group of operators are members of the stream class.

大多数运算符重载,与第二组中的运算符重载不同。

Most operator overloads, like those in the second group, are not.

对于为什么,它可能只是一个历史意外。内置类型的运算符可以添加到流类中,显然它们(早在C ++被标准化之前)。

As to the why, it is likely just a historical accident. The operators for built in types can be added to the stream classes, and obviously they were (long before C++ was standardized). The standard just documents existing practice here.

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

Operators for user defined types obviously cannot be added to the stream classes, so they are implemented as free functions.

回想起来,使所有运算符都具有自由功能更加一致,但这可能会破坏一些旧程序。

In retrospect it would have been more consistent to make all the operators free functions, but that would possibly break some old programs.

这篇关于关于ostream类和运算符&lt;&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆