iostream: istream+ostream
//读写流 #include<iostream> using namespace std; int main(){ int a, b; cin>>a>>b; cout<<a+b<<endl; return 0; }fstream:ifstream+ofstream
//读写文件 #include<fstream> using namespace std; int main(){ int a, b, c; ifstream in1; in1.open("input.txt"); ofstream out1; out1.open("output.txt", ofstream::app); in1>>a>>b; out1<<a+b<<endl; return 0; }sstream=istringstream+ostringstream
//读写字符串 #include<iostream> #include<sstream> using namespace std; int main(){ string a = "abcde"; istringstream st1; //定义输入流 st1.str(a); //拷贝内容到流中 string b = st1.str();//返回流中内容 string c; st1>>c;//输出内容到流中 ostringstream st2; //定义输出流 st2<<a<<"12345"; //输出内容到流中 string d = st2.str(); //返回流中内容 cout<<b<<" "<<c<<" "<<d<<endl; return 0; }>>运算符左侧为流输入对象,右侧为结构对象,返回一个流输入对象。 注意引用符号&
istream& operator>>(istream& in, complex& A){ in >> A.m_real >> A.m_imag; return in; }实现pair,complex类型。
#include <iostream> using namespace std; class complex{ public: complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ }; public: friend complex operator+(const complex & A, const complex & B); friend complex operator-(const complex & A, const complex & B); friend complex operator*(const complex & A, const complex & B); friend complex operator/(const complex & A, const complex & B); friend istream & operator>>(istream & in, complex & A); friend ostream & operator<<(ostream & out, complex & A); private: double m_real; //实部 double m_imag; //虚部 }; //重载加法运算符 complex operator+(const complex & A, const complex &B){ complex C; C.m_real = A.m_real + B.m_real; C.m_imag = A.m_imag + B.m_imag; return C; } //重载减法运算符 complex operator-(const complex & A, const complex &B){ complex C; C.m_real = A.m_real - B.m_real; C.m_imag = A.m_imag - B.m_imag; return C; } //重载乘法运算符 complex operator*(const complex & A, const complex &B){ complex C; C.m_real = A.m_real * B.m_real - A.m_imag * B.m_imag; C.m_imag = A.m_imag * B.m_real + A.m_real * B.m_imag; return C; } //重载除法运算符 complex operator/(const complex & A, const complex & B){ complex C; double square = A.m_real * A.m_real + A.m_imag * A.m_imag; C.m_real = (A.m_real * B.m_real + A.m_imag * B.m_imag)/square; C.m_imag = (A.m_imag * B.m_real - A.m_real * B.m_imag)/square; return C; } //重载输入运算符 istream& operator>>(istream& in, complex& A){ in >> A.m_real >> A.m_imag; return in; } //重载输出运算符 ostream& operator<<(ostream& out, complex& A){ out << A.m_real <<" + "<< A.m_imag <<" i ";; return out; } int main(){ complex c1, c2, c3; cin>>c1>>c2; c3 = c1 + c2; cout<<"c1 + c2 = "<<c3<<endl; c3 = c1 - c2; cout<<"c1 - c2 = "<<c3<<endl; c3 = c1 * c2; cout<<"c1 * c2 = "<<c3<<endl; c3 = c1 / c2; cout<<"c1 / c2 = "<<c3<<endl; return 0; }