istream/ostream与标准输入输出流
简述C++标准IO流库的层次结构。istream、ostream、iostream之间的关系是什么?cin/cout/cerr/clog分别对应什么?为什么说C++的IO是类型安全的?
回答
苦行僧
层次结构:
ios_base→basic_ios→basic_istream/basic_ostream← 模板iostream同时继承istream和ostream(钻石继承,通过虚基类解决)ifstream继承istream,ofstream继承ostream,fstream继承iostreamistringstream/ostringstream/stringstream类似
全局对象:
cin:istream,绑定到stdin,带缓冲cout:ostream,绑定到stdout,带缓冲cerr:ostream,绑定到stderr,无缓冲(每次输出立即刷新)clog:ostream,绑定到stderr,带缓冲
类型安全:
C语言的printf("%d", x)如果格式符与类型不匹配是UB。C++通过操作符重载——operator<<和operator>>——在编译期根据参数类型选择正确解析,类型不匹配直接编译错误。
自定义类型支持:
ostream& operator<<(ostream& os, const Point& p) {
return os << '(' << p.x << ',' << p.y << ')';
}
性能注意:默认cin/cout与C标准IO同步(通过ios_base::sync_with_stdio),关闭同步可提升IO速度:ios::sync_with_stdio(false); cin.tie(nullptr);。