C++之 ostream详细用法

1,180 阅读1分钟
在 C++中,ostream表示输出流,英文”output stream“的简称。在 C++中常见的输出流对象就是标准输出流cout,很少自定义ostream的对象,更多的是直接使用cout。那么 ostream 有什么用呢,来看一个场景:
[url=][/url]

1
class
CPoint
2
{
3
public
:
4
CPoint(
int
x_,
int
y_):x(x_),y(y_){}
5
int
x,y;
6
};
[url=][/url]


举个例子...这里定义了一个简单的类CPoint,如果我们实例化该类过后,想要打印对象的值:
1
CPoint point(
1
,
2
);
2
cout << point;

很明显,这样写是会报错,因为"<<"只能输出整型、实型等普通类型。错误如下:

而ostream的出现正好可以解决这个问题。
C++中的ostream这个类型,通常作为某个类的友元函数出现,用于<<操作重载中。接下来咱看看如何通过修改以上示例让输出正常流正常进行。
[url=][/url]

1
class
CPoint
2
{
3
public
:
4
CPoint(
int
x_,
int
y_):x(x_),y(y_){}
5
6
friend ostream &
operator
<<(ostream & os,
const
CPoint & p){
7
return
os <<
"
x =
"
<<p.x <<
"
y =
"
<< p.y << endl;
8
}
9
10
int
x,y;
11
};//类后面要记得加;
[url=][/url]


在 CPoint 中,我们重载了<<操作符,让其能够正常输出。
该方法还可以扩展到其他很多地方,对自定义的类型进行输出时特别管用,写法都是一样的,只要重载<<操作符,配合ostream一起使用即可。