[英]ERROR "nonstatic member reference must be relative to a specific object
#ifndef WORLD_H_
#define WORLD_H_
using namespace std;
class World{
public:
friend class DoodleBug;
friend class Ant;
friend class Organism;
int GRID_SIZE;
World();
~World();
void Draw();
int global_get_ID(int x, int y);
Organism* get_Ptr(int x, int y);
void set_Ptr(int x, int y, Organism* newOrg);
void TimeStepForward();
protected:
Organism* grid[GRID_SIZE][GRID_SIZE];
};
#endif
In this.h file on line Organism* grid[GRID_SIZE][GRID_SIZE]
I get this error: Error: a nonstatic member reference must be relative to a specific object.在
Organism* grid[GRID_SIZE][GRID_SIZE]
行的 this.h 文件中,我收到此错误:错误:非静态成员引用必须相对于特定的 object。
What does it mean and how can I fix this error?这是什么意思,我该如何解决这个错误?
The problem is that in standard C++, the size of an array must be a compile time constant .问题是在标准 C++ 中,数组的大小必须是编译时常量。 But since
GRID_SIZE
is a non-static data member, the expression GRID_SIZE
inside the class is actually equivalent to the expression this->GRID_SIZE
.但由于
GRID_SIZE
是非静态数据成员,因此 class 中的表达式GRID_SIZE
实际上等同于表达式this->GRID_SIZE
。 But the this
pointer is more of a runtime construct and the expression this->Grid_SIZE
is not a constant expression and cannot be used to specify the size of the array.但是
this
指针更像是一个运行时构造,表达式this->Grid_SIZE
不是常量表达式,不能用于指定数组的大小。
To solve this you can make the data member GRID_SIZE
a constexpr static
as shown below:要解决这个问题,您可以使数据成员
GRID_SIZE
成为constexpr static
,如下所示:
class World{
public:
//--vvvvvvvvvvvvvvvv--------------------------->constexpr static added here
constexpr static int GRID_SIZE = 10;
protected:
Organism* grid[GRID_SIZE][GRID_SIZE];
};
You can even use static const
.您甚至可以使用
static const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.