关于输入(cin)/输出(cout)的重载。
在C++的头文件中有 #include <iostream> ,实际上就包含着cin/cout,具体上:ostream中对应的是cout,而istream对应的是cin。
我先实现cout重载
#include <iostream>
using namespace std;
class Oc
{
public:
private:
int cnt;
public:
Oc( int cnt)
{
this->cnt = cnt;
}
friend ostream& operator << (ostream& ost , const Oc& oc);
};
ostream& operator << (ostream& ost , const Oc& oc)
{
ost << oc.cnt;
return ost;
}
int main()
{
system("color 5A");
Oc oc(2);
cout << oc;
return 0;
}运行结果:
解释:
①: 参数 ostream& ost , const Oc& oc 以及返回ostream& 都是使用引用 防止调用拷贝构造
②: 可以使用void返回 , 但是这样无法使用连续的输出 << oc << XXX
③: 左操作数必须是ostream对象,所以此重载必须在类外实现
cin重载:
#include <iostream>
using namespace std;
class Oc
{
private:
int cnt;
public:
Oc( int cnt)
{
this->cnt = cnt;
}
friend istream& operator >>( istream& ist , Oc& oc);
friend int main();
};
istream& operator >>( istream& ist , Oc& oc)
{
ist >> oc.cnt;
if( ist.fail() )
{
cout << "fail value to Oc.cnt!" << endl;
oc.cnt = 0;
}
return ist;
}
int main()
{
system("color 5A");
Oc oc(2);
cin >> oc;
cout << "Oc.cnt value is : " << oc.cnt << endl;
return 0;
}①,我先输入正确的值如 1 , 其结果如下:
②,在输入一个错误的值,字符串。结果如下:
ist.fail() 就是用来检测是否是输入失败的。字符串无法给int赋值。所以---
cin和cout一样只能在类外实现
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1927956
原文地址:http://aonaufly.blog.51cto.com/3554853/1927956