I want to create a class one of whose private:
members is a struct point
(see below). The public members ndim
and numparticles
开发者_运维知识库 are
set at run-time by the user, which are used to create corresponding arrays inside the class . However I am getting a compiler error. I don't understand where I messed up.
The compiler error being displayed:
nbdsearch.h:25: error: ‘point’ does not name a type
nbdsearch.h:24: error: invalid use of non-static data member ‘nbdsearch::ndim’
nbdsearch.h:31: error: from this location
nbdsearch.h:31: error: array bound is not an integer constant before ‘]’ token
The class code:
class nbdsearch{
public:
int ndim,numparticles;
point particlevec[numparticles];
private:
struct point{
string key;
double cood[ndim];
};
};
nbdsearch.h:31: error: array bound is not an integer constant before ‘]’ token
double cood[ndim];
Array size needs to be a compile time constant and ndim
clearly isn't. ndim
is a variable.
error: ‘point’ does not name a type
point particlevec[numparticles];
On line 25, compiler doesn't know what point
is. The structure is defined at a later point. Compilers in C++ work on a top to bottom approach(Not sure whether C++0X relaxes this rule). So, what ever types being used should be known to it before hand.
Try this -
class nbdsearch{
private:
struct point{
string key;
std::vector<double>cood;
};
public:
int ndim,numparticles;
std::vector<point> particlevec;
};
point
needs to be declared before its use. Try putting the private:
block before the public:
block.
There are a few different problems with your code.
The declaration of
point
needs to be visible to compiler before you use itYou're trying to create array from variables that are not compile time constants; C++ does not allow creation of variable length arrays.
To fix these problems:
Move the declaration block for
point
above where you use it. Note that since the definition ofpoint
isprivate
, someone callingnbdsearch::particlevec
will not be able to store that value. All they could do is pass it along to another member function (orfriend
function) ofnbdsearch
.Change declaration of
particlevec
tostd::vector<point> particlevec
. Make a similar change forpoint::cood
. Once the user specifies values forndim
&numparticles
usestd::vector::resize
to size the arrays appropriately.
精彩评论