cin是istream类下的对象,cout是ostream类的对象,这两个类都在头文件<iostream>里面
在理解cin功能时,不得不提标准输入缓冲区。当我们从键盘输入字符串的时候需要敲一下回车键才能够将这个字符串送入到缓冲区中,那么敲入的这个回车键(\r)会被转换为一个换行符\n,这个换行符\n也会被存储在cin的缓冲区中并且被当成一个字符来计算!比如我们在键盘上敲下了123456这个字符串,然后敲一下回车键(\r)将这个字符串送入了缓冲区中,那么此时缓冲区中的字节个数是7 ,而不是6。
cin可以连续从键盘读取想要的数据,以空格、tab或换行作为分隔符。实例程序如下。
#include <iostream>
using namespace std;
int main()
{
char a;
int b;
float c;
string
cin>>a>>b>>c;
cout<<a<<" "<<b<<" "<<c<<" "<<endl;
system("pause");
return 0;
}
在屏幕中一次输入:a[回车]11[回车]5.56[回车],程序将输出如下结果:
说明一下,为什么我们平常觉得cout和cin可以自己识别类型,实际上是有各种各样的函数重载,参数的类型都不相同
当然我们也可以自己写输出输入流,不用自带的cin和cout。下面代码是可以正常运行的
class Date{
public:
Date(int year, int month, int day){
_year = year;
_month = month;
_day = day;
}
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
return in;
}
private:
int _year;
int _month;
int _day;
}
int main(){
Date d1(2023, 5, 5);
// 流插入
cout << d1;
operator<<(cout, d1);
}
说一下这里的const,首先ostream和istream之前不能加const,因为底层代码运作的时候istream会改变里面的东西,如果加了const就不能插入值了,ostream也需要先插入,同理不能加const。
当然还有最简便的写法,但是这种就不符合我们平常的使用习惯,看看即可
ostream& operator<<(ostream& out)
{
out << _year << "年" << _month << "月" << _day << "日" << endl;
return out;
}
int main(){
d1 << cout;
d1.operator<<(cout);
}
还有个const的点要注意一下
bool Date::operator<(const Date& x) const
{
if (_year < x._year)
{
return true;
}
else if (_year == x._year && _month < x._month)
{
return true;
}
else if (_year == x._year && _month == x._month && _day < x._day)
{
return true;
}
return false;
}
int main(){
Date d1(2023, 5, 5);
const Date d2(2023, 5, 5);
d1 < d2;
d2 < d1;//如果上面那个成员函数的右边没有加const这里会报错,因为权限放大了,这是不可以的,这个const修饰的是主体
}