面试题答案
一键面试- 继承的类:
- 应继承自
std::streambuf
类。std::streambuf
是C++ 输入输出流库中负责缓冲区管理的基类。
- 应继承自
- 需要重写的关键函数:
overflow(int_type c = traits_type::eof())
:- 此函数在缓冲区已满,需要向其中插入新字符时被调用。
- 实现时,需要检查缓冲区是否还有空间,若没有则处理缓冲区数据(比如记录长度并打印),然后尝试为新字符开辟空间。
- 示例代码(伪代码):
int_type overflow(int_type c = traits_type::eof()) {
if (c != traits_type::eof()) {
// 检查缓冲区是否已满,这里假设缓冲区大小固定为bufSize
if (next_free - buffer >= bufSize) {
// 记录当前缓冲区数据长度
std::size_t length = next_free - buffer;
std::cout << "Data length written so far: " << length << std::endl;
// 处理缓冲区数据(比如清空缓冲区为新数据做准备)
next_free = buffer;
}
*next_free++ = traits_type::to_char_type(c);
}
return c;
}
sync()
:- 此函数用于将缓冲区中的数据同步到外部存储(比如文件、字符串等)。
- 在我们的场景下,需要确保缓冲区中剩余的数据也被正确处理(记录长度并打印)。
- 示例代码(伪代码):
int sync() {
if (next_free - buffer > 0) {
std::size_t length = next_free - buffer;
std::cout << "Data length in buffer during sync: " << length << std::endl;
// 可以选择清空缓冲区
next_free = buffer;
}
return 0;
}
- 将自定义流缓冲区与
ostringstream
关联起来:- 可以使用
ostringstream
的rdbuf()
成员函数。 - 示例代码:
- 可以使用
#include <sstream>
#include <iostream>
class MyStreamBuf : public std::streambuf {
// 上面定义的overflow和sync函数等
};
int main() {
MyStreamBuf myBuf;
std::ostringstream oss;
oss.rdbuf(&myBuf);
oss << "Hello, World!";
return 0;
}
在上述代码中,通过oss.rdbuf(&myBuf)
将自定义的MyStreamBuf
与ostringstream
对象oss
关联起来,这样oss
输出的数据就会经过MyStreamBuf
,进而触发我们重写的函数来记录数据长度并打印。