次のプログラムが正しく機能するかどうかを確認するテスターを作成しようとしていますが、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 で実行しました。