How can I allocate an array of object inside another class in it's constructor?
class BloomFilter
{
public:
BloomFilter(double fp, size_t capacity);
private:
size_t bf_m;
size_t bf_k;
};
class RSig {
public:
RSig(int32_t sizeL1, int32_t sizeL2, double bfFpRate) :
numSlot_sig(sizeL1), numSlot_bf(sizeL2)
{
TL_sigMem = new BloomFilter(bfFpRate, numSlot_bf)[sizeL1];
}
private:
int32_t numSlot_sig, numSlot_bf;
BloomFilter* TL_sigMem;
};
The code above gives me the following error:
In constructor 'RSig::RSig(int32_t, int32_t, double)’:
error: expected ‘;’ before ‘[’ token
TL_sigMem = new TL_sigMem(bfFpRate, numSlot_bf)[sizeL1];
Preferably, I don't want to use std::vector
.
Like this:
#include <vector>
class RSig
{
public:
RSig(double rate, std::size_t len) : TL_sigMen(len, BloomFilter(rate)) {}
private:
std::vector<BloomFilter> TL_sigMem;
};
To create an array of objects, the syntax goes like this:
T* t = new T[<size>];
Where T
is the type, t
is the name of the array, and <size>
is the size of the array. Now, in your situation, you would like to do this:
TL_sigMem = new BloomFilter[sizeL1];
This will create an array of BloomFilter
s of size sizeL1
. However, since your BloomFilter
does not seem to have a default constructor, you'll need to either use std::vector
and its emplace_back()
function, whip out your own (rather complicated) approach, or to create an array of pointers instead:
BloomFilter** TL_sigMem;
TL_sigMem = new BloomFilter*[sizeL1];
TL_sigMem[0] = new BloomFilter(...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.