#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
在 Organism* grid[GRID_SIZE][GRID_SIZE]
行的这个 .h 文件中,我收到此错误:错误:非静态成员引用必须相对于特定对象。
这是什么意思,我该如何解决这个错误?
回答1
问题是在标准 C++ 中,数组的大小必须是编译时间常数。但是由于 GRID_SIZE
是一个非静态数据成员,所以类中的表达式 GRID_SIZE
实际上等价于表达式 this->GRID_SIZE
。但是 this
指针更多是运行时构造,表达式 this->Grid_SIZE
不是常量表达式,不能用于指定数组的大小。
要解决此问题,您可以将数据成员 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];
};
您甚至可以使用 static const
。