自定义实现输入输出模版的一个例子

 #include<iostream>
#include<string>
using namespace std;

class Object;



class Input{

	public:
		Input(){
		cout<<"Input Constructor"<<endl;
	}
	template<class T>
	Input & operator>>(T &o)
	{
		if(typeid(T).name()!=typeid(string).name())
			cin>>o;
		else
		{
			//cin.getline(o,100);//wrong
			//cin.get(o,100,'\n');//wrong
			//cout<<"OK"<<endl;
			//std::getline(cin,o,'\n');//wrong
			//getline(cin,o);
			cin>>o;
		}
		//cout<<"typeid="<<typeid(T).name()<<endl;
		
			//cin.get(o);

			
		return *this;
	}

};

class Output
{
	public:
		Output(){
		cout<<"Output Constructor"<<endl;
	}
	template<class T>
	Output &operator<<(T &o)
	{
		cout<<o;
		return *this;

	}
};

Input in;
Output out;

class Object
{
	int a;
	int b;
	int c;
	string s;
	public:
	

	Object(int a_=10,int b_=100,int c_=1000,string s_="'hello world'"):a(a_),b(b_),c(c_),s(s_){}

	Output &operator<<(Output &output)
	{
		output<<a<<" "<<b<<" "<<c<<" "<<s;
		return output;
	}
	Input &operator>>(Input &input)
	{
		input>>a>>b>>c>>s;
		return input;
	}
	void printf(){
		cout<<a<<' '<<b<<' '<<c<<' '<<s<<endl;
	}

};




int main()
{

	Object obj1;
	obj1.printf();
	//in>>obj1; //如要实现此种输入输出须用友元函数实现
	//out<<obj1;
	obj1.operator>>(
		in);
	obj1.operator<<(out);;
	cout<<endl<<'A'<<endl;
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值