#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;
}
自定义实现输入输出模版的一个例子
最新推荐文章于 2021-05-17 19:36:59 发布