在一个简单的猎人/猎物模拟中,我到处都遇到了奇怪的编译错误(主要是因为教授没有很好地解释继承类和虚函数的语法),我完全陷入了一个问题。Move()
在这个程序中,“Creatures”(一个带有“Hunter”和“Prey”孩子的抽象类)在一个, Breed()
,中的一个“Grid”类中走动Die()
循环
我收到以下错误:“C2027:使用未定义类型'Creature'”和“C2227:'->face'左侧必须指向类/结构/联合/通用类型”在下面指定的行(所有我的代码在标题中,因为有几个学生在另一个项目中得到了未解决的外部问题,教授告诉我们把它全部放在标题中)。如果我需要发布更多代码,请告诉我。
我遇到了其他几个在此之前无法解释的错误,这些错误似乎是通过添加/删除包含的标头和预声明类的看似随机组合来解决的,但是非常感谢对发生了什么问题的实际解释所以在它起作用之前,我不只是在黑暗中挣扎。我了解我们正在尝试做的事情的概念,甚至在很大程度上了解如何去做,但正如我所提到的,我们没有花任何时间在如何正确设置多个文件的语法上,以便每个人工作顺利,因此将不胜感激任何有关如何完成此操作的详细说明。
网格.h
#ifndef GRID_H
#define GRID_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "creature.h"
using namespace std;
class Creature;
class Grid
{
public:
Creature* grid[MAX_X][MAX_Y];
Grid() //Initalizes the grid and spawns random creatures
{
for(int i = 0; i < MAX_X; i++)
for(int j = 0; j < MAX_Y; j++)
grid[i][j] = NULL;
}
void Move() //Tells each creature on the grid to move
{
//Call creature.Move() on each cell (if not NULL)
}
void Breed() //Tells each creature to breed (if it can)
{
//Call creature.Breed() on each cell (if not NULL)
}
void Kill() //Tells each creature to die (if it's old)
{
//Call creature.Die() on each cell (if not NULL)
}
char** Snapshot() //Creates a char array "snapshot" of the board
{
//Produces a 2D char array of the grid for display
}
Creature* Get(Coords here) //Returns a pointer to the object at the specified position
{
return grid[here.x][here.y];
}
char Occupant(Coords here) //Returns the character of the specified position
{
if(!Get(here))
return FACE_EMPTY;
Creature* temp = Get(here);
return temp->face; //*** ERRORS APPEAR HERE ***
}
void Clear(Coords here) //Deletes the object at the specified position
{
if(Get(here))
delete Get(here);
grid[here.x][here.y] = NULL;
}
};
#endif // GRID_H
生物.h
#ifndef CREATURE_H
#define CREATURE_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "coords.h"
#include "grid.h"
using namespace std;
class Grid;
class Creature
{
public:
Grid* theGrid;
Coords position;
int stepBreed;
int stepHunger;
char face;
Creature(Grid* _grid, Coords _position, char _face) //Constructor
{
theGrid = _grid;
position = _position;
face = _face;
stepBreed = stepHunger = 0;
}
virtual Coords Move() = 0; //Allows the child to define it's own movement
virtual Coords Breed() = 0; //Allows the child to define it's own breeding
virtual bool Starve() = 0; //Allows the child to starve of its own accord
};
#endif // CREATURE_H