编译器说变量不是类的成员

时间:2013-11-03 22:21:31

标签: c++ compiler-errors

我在网格的默认构造函数的前两行中收到编译器错误“错误:wall不是Grid的成员”。我不确定为什么它说我在头文件中定义了墙和网格!我也尝试过使用this-> wall,Grid :: wall和初始化列表。这是代码:

Grid::Grid() {
    this->wall = Species("wall");
    this->empty = Species("empty");
    Grid::turn_number = 0;
    int a,b;
    for(a= 0; a < 100; a++)
        for(b = 0; b< 100; b++) {
            Creature empty_creature = Creature(Grid::empty,a,b,NORTH,this);
            ((Grid::map)[a][b]) = empty_creature;
        }
    Grid::width = 0;
    Grid::height = 0;
}

当我将默认构造函数更改为使用初始化列表时,我得到了同样的错误:

Grid::Grid()
: width(0), height(0), turn_number(0), wall("wall"), empty("empty"){
    int a,b;
    for(a= 0; a < 100; a++)
        for(b = 0; b< 100; b++) {
            Creature empty_creature = Creature(Grid::empty,a,b,NORTH,this);
            ((Grid::map)[a][b]) = empty_creature;
        }
}

在页眉文件中:

class Grid {
protected:
    Creature map[100][100];
    int width,height;
    int turn_number;
    Species empty;
    Species wall;
public:
    Grid();
    Grid(int _width, int _height);
    void addCreature(Species &_species, int x, int y, Direction orientation);
    void addWall(int x, int y);
    void takeTurn();
    void infect(int x, int y, Direction orientation, Species &_species);
    void hop(int x, int y, Direction orientation);
    bool ifWall(int x, int y, Direction orientation);
    bool ifEnemy(int x, int y, Direction orientation, Species &_species);
    bool ifEmpty(int x, int y, Direction orientation);
    void print();
};

这是我的其余编译器错误(在评论中要求)。抱歉格式化,我的电脑由于某种原因吐出奇怪的字符。

Darwin.c++: In constructor ‘Grid::Grid()’:
Darwin.c++:8:40: error: class ‘Grid’ does not have any field named ‘wall’
Darwin.c++:8:54: error: class ‘Grid’ does not have any field named ‘empty’
Darwin.c++:12:39: error: ‘empty’ is not a member of ‘Grid’
Darwin.c++: In constructor ‘Grid::Grid(int, int)’:
Darwin.c++:17:86: error: class ‘Grid’ does not have any field named ‘wall’
Darwin.c++:17:99: error: class ‘Grid’ does not have any field named ‘empty’
Darwin.c++:21:39: error: ‘empty’ is not a member of ‘Grid’
Darwin.c++: In member function ‘void Grid::addWall(int, int)’:
Darwin.c++:32:31: error: ‘wall’ is not a member of ‘Grid’
Darwin.h:35:10: error: field ‘empty’ has incomplete type
Darwin.h:36:10: error: field ‘wall’ has incomplete type
In file included from RunDarwin.c++:33:0:
Darwin.h:35:10: error: field ‘empty’ has incomplete type
Darwin.h:36:10: error: field ‘wall’ has incomplete type

2 个答案:

答案 0 :(得分:3)

“包含不完整类型”表示您没有为编译器提供Species的定义。如果没有定义,最多可以指向数据,因为编译器不知道要保留多少空间。所以它给出了一个错误,然后忽略该行并尝试理解程序的其余部分。当然,因为该行被忽略了,以后尝试使用它会失败。

请注意,您的编辑器已按文件名对错误进行了排序,而不是向您显示实际发生的顺序。将来,请按顺序查看编译器输出。

通过在Species之前设置class Grid的定义(或#include),可以轻松解决这个问题。

答案 1 :(得分:-1)

您正在使用static(或类)变量的语法,但这些是实例变量。试试这个

Grid::Grid() {
    this->wall = Species("wall");
    this->empty = Species("empty");
    this->turn_number = 0;