- 字节流可以是任何在内存存储的信息。
- cin是类istream的对象,cout是类ostream的对象。
- '>>‘和’<<'能自动识别输入输出类型。
- 重载插入和抽取运算符的重载只能用友元函数形式重载,因为这些对象不是自定义的。
- 重载函数格式:
ostream& operator <<(ostream& stream, const 类名 &obj){
return stream;
}
friend ostream& operator <<(ostream& stream, const Complex& obj){
stream << obj.real << obj.image;
return stream;
}
istream& operator >>(istream& stream, 类名 &obj){
return stream;
}
friend istream& operator >>(istream& stream, Complex& obj){
cout << "please input the real and the image" << endl;
stream >> obj.real;
stream >> obj.image;
return stream;
}
- 注意:
(1)在重载函数内部并不是不能使用cin和cout对象,要根据具体情况和程序员的需求来使用。
(2)函数返回值为流的引用能支持连续的输入输出。
Complex obj1, obj2;
cin >> obj1 >> obj2;
cout << obj1 << endl << obj2 << endl;
- 格式化成员函数
int a = 1234;
cout.width(8);
cout << a;
- 注意:有些函数一旦调用后面就一直生效,但有些只生效一次。
- ios类的操纵符
- 不带参数的操纵符在iostream.h的头文件中,带参数的在iomanip.h中。
- 使用方式
double a = 3.1415;
cout << setprecision(2) << a;
- get / getline(char*, stringlength, 分隔符)
- get的分割符不会插入数组,但会留在缓冲流中,若接下来还有字符输入就会接受到分隔符。而getline会直接丢掉分隔符,不会出现这种情况。
- 重载输出运算符时,如果后面不是单纯的类,而是类运算,在重载时参数类型不能是引用。
cout << obj1 + obj2 << endl;
ostream& operator <<(ostream&, className&)
ostream& operator <<(ostream&, className)