'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.
What does it mean and how can I fix this error?
Solution 1:[1]
The problem is that in standard C++, the size of an array must be a compile time constant. 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. 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.
To solve this you can make the data member GRID_SIZE a constexpr static as shown below:
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
