我正在尝试为以下程序编写一个测试程序,以查看它是否正常运行,但是,我不确定我是否正确实现了 flush() 并且由于某种原因我没有得到任何输出。有人可以建议代码来测试这个类,看看我是否正确实现了flush和writeBit?
#ifndef BITOUTPUTSTREAM_HPP
#define BITOUTPUTSTREAM_HPP
#include <iostream>
class BitOutputStream {
private:
char buf; // one byte buffer of bits
int nbits; // how many bits have been written to buf
std::ostream& out; // reference to the output stream to use
public:
/* Initialize a BitOutputStream that will
* use the given ostream for output.
* */
BitOutputStream(std::ostream& os) : out(os) {
buf = nbits = 0; // clear buffer and bit counter
}
/* Send the buffer to the output, and clear it */
void flush() {
out.put(buf);
// EDIT: removed flush(); to stop the infinite recursion
buf = nbits = 0;
}
/* Write the least sig bit of arg into buffer */
int writeBit(int i) {
// If bit buffer is full, flush it.
if (nbits == 8)
flush();
// Write the least significant bit of i into
// the buffer at the current index.
// buf = buf << 1; this is another option I was considering
// buf |= 1 & i; but decided to go with the one below
int lb = i & 1; // extract the lowest bit
buf |= lb << nbits; // shift it nbits and put in in buf
// increment index
nbits++;
return nbits;
}
};
#endif // BITOUTPUTSTREAM_HPP
我作为测试人员写的是:
#include "BitOutputStream.hpp"
#include <iostream>
int main(int argc, char* argv[])
{
BitOutputStream bos(std::cout); // channel output to stdout
bos.writeBit(1);
// Edit: added lines below
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(1);
// now prints an 'A' ;)
return 0;
}
我知道这是错误的,因为我没有得到任何输出并且无法查看实现是否正确。感谢您提供的任何意见。
我用: g++ -std=c++11 main.cpp BioOutputStream.hpp BitInputStream.cpp 编译了代码并用: ./a.out 运行它