Question

I have a class in a header file called bitarray.h and a corresponding bitarray.cpp and I also have a sieve.h. The sieve.h and bitarray.cpp #includes the bitarray.h and sieve.h only has a function void Sieve(BitArray a). I would like to call Set() and Unset() which are declared in bitarray.h and defined in bitarray.cpp from the Sieve function but it will not let me. How do I fix this.

    //sieve.h
    #include "bitarray.h"
    #include <cmath>

    using namespace std;

    void Sieve(BitArray a)
    {
   //initialize all to 1
   for (int i = 0; i < (a.arraySize*a.unsChar*8); i++)
   {
    a.Set(i);
   }

   //unset 0 and 1 becasue they are never prime
   a.Unset(0);
   a.Unset(1);
   //leave 2 as a 1
       /*for (int i = 2; i < (a.arraySize*a.unsChar*8); i++)
    a.Unset(2*i);*/
    }
Was it helpful?

Solution

Those functions, unless declared in the bitarray.h header, are local to the bitarray.cpp. If you want access to them in sieve.h, declare them in the bitarray.h header, or in another file accessible by sieve.cpp/sieve.h.

// bitarray.h
class BitArray
{
public:
  void Set(); // Example.
  void Unset(); // Example.
};

// sieve.h
#include bitarray.h
void Sieve(BitArray a)
{
  a.Set();
  a.Unset();
}

EDIT:

I'm pretty certain that the issue you're having, is that you're not seeing changes to your BitArray object because you're passing a copy of the original. Any changes you make to it in the Sieve() function won't be reflected in the original object.

Try passing the BitArray object by reference:

void Sieve(BitArray& a)
{
  ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top