C++中cin/cout和流符号的原理(对重载输入输出流比较有用)

cin/cout并不是C++的关键字,而是对象。

C++的<iostrem>中,有一个istream类和一个ostream类,而cin就是istream类的对象,cout就是ostream类的对象。

流符号是怎样实现的呢?

C++支持重载运算符,而流符号(<<、>>)就是重载了左移和右移运算符的结果。i/ostream类有多个左移/右移运算符,用来输入/输出不同类型的变量。

endl、flush这样的效果是怎样实现的呢?我想,应该是用函数指针的方式实现的。即把左移、右移的参数定为函数指针,而endl、flush等就是你传入的函数。

而setprecision(n)带括号的形式是怎么来的呢?我想到了一种方法。(注意可能实际不是,但是可以用这种方法实现)可以把setprecision函数的返回类型设为一个结构体,然后在这个结构体中重载()运算符,这样就变成了一个仿函数,就可以在输入输出流中使用带括号的函数了。

另外,重载输入输出流时要注意设置为友元函数,第一个参数为i/ostream,第二个参数如果是输入,加上&引用;如果是输出,不要加引用,因为你可能会输出一些临时值,比如a+b的结果。


最后附上我用以上分析制造出来的my_i/ostream(输入输出采用scanf/printf函数):

//myio.h
#ifndef MYIO_H
#define MYIO_H
#include<cstdio>
#include<cstring>
#include<string> //one of I/O type 
#ifndef I_CSTR_MAX_SIZE
	#define I_CSTR_MAX_SIZE 1003
#endif
using std::scanf;
using std::printf;
using std::freopen;
using std::fclose;
using std::string;
void flush(){}
int endl(){}
struct set_precision_class{
	struct setp_num{
		int number;
	};
	setp_num operator () (int numbers){
		setp_num ans={numbers};
		return ans;
	}
}set_precision; 
struct oct_class{
	struct oct_type{
		unsigned int number;
	};
	oct_type operator () (int numbers){
		oct_type ans={numbers};
		return ans;
	}
}octal;
struct hex_class{
	struct hex_type{
		unsigned int number;
	};
	hex_type operator () (int numbers){
		hex_type ans={numbers};
		return ans;
	}
}hexal;
struct f_open_class{
	struct open_type{
		char* name;
	};
	open_type ope
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值