在 C++中,ostream表示输出流,英文”output stream“的简称。在 C++中常见的输出流对象就是标准输出流cout,很少自定义ostream的对象,更多的是直接使用cout。那么 ostream 有什么用呢,来看一个场景:
class CPoint
{
public:
CPoint(int x_,int y_):x(x_),y(y_){}
int x,y;
};
这里定义了一个简单的类CPoint,如果我们实例化该类过后,想要打印对象的值:
CPoint point(1,2);
cout << point;
很明显,这样写是会报错,因为"<<"只能输出整型、实型等普通类型。错误如下:
这时,可以写
class CPoint
{
public:
CPoint(int x_,int y_):x(x_),y(y_){}
friend ostream & operator <<(ostream & os,const CPoint & p){
return os << "x = "<<p.x << " y = "<< p.y << endl;
}
int x,y;
};
另一个例子
class TestLog//日志类
{
public:
template<typename T>
TestLog(const T &t) {
_ss << t;
};
~TestLog() {};
//通过此友元方法,可以打印自定义数据类型
friend ostream& operator<<(ostream& out, const TestLog& obj) {
return out << obj._ss.str();
}
private:
stringstream _ss;
};
int main()
{
CPoint point(1, 2);
cout << point;
cout << TestLog((int)100) << endl;
}
输出:
参考: