简体   繁体   English

C ++如何使用头文件中的cpp文件中的函数

[英]C++ How to use functions from a cpp file in a header file

I have a class in a header file called bitarray.h and a corresponding bitarray.cpp and I also have a sieve.h. 我在名为bitarray.h的头文件和相应的bitarray.cpp中有一个类,并且我也有一个sieve.h。 The sieve.h and bitarray.cpp #includes the bitarray.h and sieve.h only has a function void Sieve(BitArray a). sieve.h和bitarray.cpp#包含bitarray.h和sieve.h仅具有函数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. 我想从Sieve函数中调用在bitarray.h中声明并在bitarray.cpp中定义的Set()和Unset(),但它不会让我这样做。 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);*/
    }

Those functions, unless declared in the bitarray.h header, are local to the bitarray.cpp . 除非在bitarray.h标头中声明,否则这些函数是bitarray.h的本地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 . 如果要在sieve.h访问它们,请在bitarray.h标头中或在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 . 我可以肯定的是,您遇到的问题是您没有看到对BitArray对象的更改,因为您正在传递原始的副本 Any changes you make to it in the Sieve() function won't be reflected in the original object. 您在Sieve()函数中对其所做的任何更改都不会反映在原始对象中。

Try passing the BitArray object by reference: 尝试通过引用传递BitArray对象:

void Sieve(BitArray& a)
{
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM