C++成员是结构的类:无法理解编译器错误
我想创建一个类,其 private:
成员之一是 struct point
(见下文)。公共成员 ndim
和 numarticles
是 由用户在运行时设置,用于在类中创建相应的数组。但是我收到编译器错误。我不明白我哪里搞砸了。
显示的编译器错误:
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
类代码:
class nbdsearch{
public:
int ndim,numparticles;
point particlevec[numparticles];
private:
struct point{
string key;
double cood[ndim];
};
};
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];
};
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
您的代码存在一些不同的问题。
point
的声明需要对编译器可见
你使用它你试图从不是编译时常量的变量创建数组; C++ 不允许创建可变长度数组。
要解决这些问题,请执行以下操作:
将
point
的声明块移至您使用它的位置上方。请注意,由于point
的定义是private
,因此调用nbdsearch::articlevec
的人将无法存储该值。他们所能做的就是将其传递给nbdsearch
的另一个成员函数(或friend
函数)。将
particlevec
的声明更改为std::vector
;粒子向量。对 point::cood
进行类似的更改。一旦用户指定了 ndim 和 ndim 的值,numarticles
使用std::vector::resize
适当调整数组大小。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
数组大小需要是编译时常量,而 ndim 显然不是。
ndim
是一个变量。在第 25 行,编译器不知道
point
是什么。该结构稍后定义。 C++ 中的编译器采用自上而下的方法工作(不确定 C++0X 是否放宽了此规则)。因此,无论使用什么类型,都应该事先知道。试试这个 -
Array size needs to be a compile time constant and
ndim
clearly isn't.ndim
is a variable.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 -