我正在为我的OO课程编写一个程序,而且我的cout语句遇到了一些问题。程序应该接受一个值并将其转换为按位数组。我的问题是,无论我输入什么数字,它都会将数组中的每个元素cout为0.赋值表示在构造函数中将每个元素初始化为0,但是将它与&在Query函数中,运算符只能返回false。有什么建议? (注意:我们不能使用矢量或任何预制函数。)
头文件中的:
private:
static const CSIZE = 8 * sizeof(char);
int arraySize;
unsigned char* barray;
在.cpp文件中
#include <iostream>
#include "bitarray.h"
using namespace std;
ostream& operator<< (ostream& os, const BitArray& a)
{
for (unsigned int i = 0; i < a.arraySize * a.CSIZE; i++)
os << a.Query(i);
return os;
}
BitArray::BitArray(unsigned int n)
{
if (n % CSIZE != 0)
arraySize = (n / CSIZE) + 1;
else
arraySize = n / CSIZE;
barray = new unsigned char[arraySize];
for (int i = 0; i < arraySize; i++)
barray[i] = 0;
}
unsigned char BitArray::Mask (unsigned int num) const
{
return (1 << num % CSIZE);
}
void BitArray::Set (unsigned int index)
{
unsigned int i = index / CSIZE;
barray[i] |= Mask (index);
}
bool BitArray::Query (unsigned int index) const
{
unsigned int i = index / CSIZE;
if (barray[i] & Mask (index))
return true;
return false;
}
主程序:
#include <iostream>
using namespace std;
#include "sieve.h"
#include "bitarray.h"
int main()
{
unsigned int i, max, counter = 0;
cout << "\nEnter a positive integer for the maximum value: ";
cin >> max;
BitArray ba(max);
Sieve(ba); // find the primes (marking the bits)
cout << "The bit array looks like this: \n"
<< ba
<< '\n';
cout << "\nPrimes less than " << max << ':' << '\n';
for (i = 0; i < max; i++)
{
if (ba.Query(i))
{
counter++;
cout << i;
if (counter % 8 == 0)
{
cout << '\n';
counter = 0;
}
else
cout << '\t';
}
}
cout << "\nGoodbye!\n";
return 0;
}