开发者

C++ class whose member is a struct: Cannot understand compiler error

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.

  1. The declaration of point needs to be visible to compiler before you use it

  2. You'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:

  1. Move the declaration block for point above where you use it. Note that since the definition of point is private, someone calling nbdsearch::particlevec will not be able to store that value. All they could do is pass it along to another member function (or friend function) of nbdsearch.

  2. Change declaration of particlevec to std::vector<point> particlevec. Make a similar change for point::cood. Once the user specifies values for ndim & numparticles use std::vector::resize to size the arrays appropriately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜