C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。您可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。
输出运算符
cout是ostream的一个对象
#include <iostream>
using namespace std;
class cstu
{
private:
int nage;
cstu()
{
nage = 12;
}
friend void operator <<(ostream& os, const cstu &st);//通常类内的变量都为private,用友元函数可以解决这个问题
};
void operator <<(ostream& os, const cstu &st)//输出运算符必须放在类外
{
os << st.nage;
}
int main()
{
cstu st;
cout << st;
return 0;
}
在进行连续的输出时,例如cout <<st<<st;,函数必须有返回值
输入运算符
cout是istream的一个对象
#include <iostream>
using namespace std;
class cstu
{
public:
int nage;
double dbHeight;
cstu()
{
nage = 12;
dbHeight = 1.7;
}
void show()
{
cout << nage << dbHeight << endl;
}
friend istream& operator >> (istream& ist, cstu &st);
};
istream& operator >> (istream& ist, cstu &st)
{
ist >> st.nage >> st.dbHeight;
}
int main()
{
cstu st;
cin >> st;
st.show();
return 0;
}
有一个可以判断用户是否输入有误的函数
istream& operator >> (istream& ist, cstu &st)
{
ist >> st.nage >> st.dbHeight;
if (ist.fail())
{
cout << "error" << endl;
}
return ist;
}
若输入的数值形式有误,则输出error
也可以直接将变量的值返回初始值
istream& operator >> (istream& ist, cstu &st)
{
ist >> st.nage >> st.dbHeight;
if (ist.fail())
{
nage = 12;
dbHeight = 1.7;
}
return ist;
}