C++ostream的使用

在 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;
}

输出:

参考:

C++之 ostream详细用法_luoyayun361的博客-CSDN博客_c++ ostream

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值