c++中ostream类的超详细说明

本文详述C++标准输出流类ostream,涵盖构造函数、<<操作符、put、write、flush、tellp和seekp等成员函数的用法。通过实例解析其功能和应用场景,帮助理解ostream如何实现标准输出及文件输出。
摘要由CSDN通过智能技术生成

根据前文,ostream类是c++标准输出流的一个基类,本篇详细介绍ostream类的主要成员函数用法。

1.ostream的构造函数

从ostream头文件中截取一部分关于构造函数的声明和定义,如下:

public:
//explicit用来防止由构造函数定义的隐式转换
explicit
      basic_ostream(__streambuf_type* __sb)
      {
    this->init(__sb); }

protected:
      basic_ostream()
      {
    this->init(0); }

#if __cplusplus >= 201103L
      // Non-standard constructor that does not call init()
      basic_ostream(basic_iostream<_CharT, _Traits>&) {
    }

      basic_ostream(const basic_ostream&) = delete;

      basic_ostream(basic_ostream&& __rhs)
      : __ios_type()
      {
    __ios_type::move(__rhs); }

      // 27.7.3.3 Assign/swap

      basic_ostream& operator=(const basic_ostream&) = delete;

      basic_ostream&
      operator=(basic_ostream&& __rhs)
      {
   
	swap(__rhs);
	return *this;
      }

可以看到ostream类的默认构造函数是保护类型,而带参数的构造函数则是公有的,根据public和protected的功能,我们要定义一个ostream对象,必须要在参数中传入streambuf类型的指针才可以,否则会报编译错误。

一个可用的例子如下:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
   
	filebuf buf;
	if ( buf.open("/proc/self/fd/1", ios::out) == nullptr )
	{
   
		cerr << "stdout open failed" << endl;
		return -1;
	}
	ostream out(&buf);
	
  • 13
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp加油站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值