C++流 输入输出流
流的概念:
C++ 键盘输入到变量, 然后变量不断流向输出设备, 因此称为输入输出流
setf()函数用来设置流状态标识的
unsetf() 函数 是cout 的成员函数 用来解除当前设置的
#include<iostream>
using namespace std;
int main()
{
double x = 1.0000234;
double y = 1.2345678;
cout<<"默认格式:"<<endl;
cout<<"x = "<<x<<" y = "<<y<<endl;
cout<<"科学计数法:"<<endl;
cout.setf(ios::scientific);
cout<<"x = "<<x<<" y = "<<y<<endl;
cout<<"恢复默认格式:"<<endl;
cout.unsetf(ios::scientific);
cout<<"x = "<<x<<" y = "<<y<<endl;
return 0 ;
}
插入符号<< 的标准格式
friend ostream & operator <<(ostream &stream, 类名 &类引用名)
{
函数体;
return stream;
}
看类子:
#include<iostream>
using namespace std;
class myclass
{
int x, y;
public:
myclass(int m , int n){x = m ; y = n;}
friend ostream & operator <<(ostream & stream,myclass &s)
{
//这里面添加的是函数体
cout<<"x = "<<s.x<<" y = "<<s.y<<endl;
return stream;
}
};
int main()
{
myclass A(2, 3),b(23,14);
cout<<A<<b<<endl;
}
提取运算符重载:
>> 称为是提取运算符, 对他进行重载的函数是提取符号函数
标准和格式:
friend istream & operator >>(ostream &stream, 类名 &类引用名)
{
函数体;
return stream;
}
请看例子:#include<iostream>
using namespace std;
class myclass
{
int x , y;
public:
myclass(){}
friend istream & operator>>(istream &stream, myclass &s)
{
//函数体
cout<<"输入x 和y 的值:"<<endl;
cout<<"x = ";
cin>>s.x;
cout<<"y = ";
cin>>s.y;
return stream;
}
//下面是输出x和y 的值
friend ostream & operator <<(ostream &stream, myclass &s)
{
cout<<"输出x 和 y 的值:"<<endl;
cout<<"x = "<<s.x<<" y = "<<s.y<<endl;
return stream;
}
};
int main()
{
myclass a;
cin>>a;
cout<<a;
return 0;
}