您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
关于输入(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一样只能在类外实现
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。