我有一个二维数组,应该用来存放不断移动的物体。
class ZombieLand : public Singleton<ZombieLand>
{
DECLARE_SINGLETON(ZombieLand);
public:
MachineState world [19][19];
MachineState getWorld()
{
std::cout<<"World";
return world[19][19];
}
void setWorld(MachineState & state)
{
world [state.x][state.y] = state;
}
}
我尝试检查某个位置是否为 Null,但是“NULL”这个词不起作用,0 也不起作用
switch (state.m_Facing)
{
case (MachineState::UP):
if(ZombieLand::get().world[state.x][state.y-1] != NULL )
{
state.m_occupied = true;
break;
}
我的问题是,如何检查我的世界数组的某个位置是否已经包含一个对象?在此先感谢您。
我的 MachineState 类
struct MachineState
{
template <typename MachineTraits>
friend class Machine;
enum Facing { UP, RIGHT, DOWN, LEFT};
MachineState()
: m_ProgramCounter(1)
, m_ActionsTaken(0)
, m_Facing(UP)
, m_Test(false)
, m_Memory(nullptr)
,x(0)
,y(0)
,point1(25, 10)
,point2(10, 40)
,point3(40, 40)
{ }
int m_ProgramCounter;
int m_ActionsTaken;
Facing m_Facing;
bool m_Test;
bool m_occupied;
int x;
int y;
Point point1;
Point point2;
Point point3;
int GetActionsPerTurn() const throw() { return m_ActionsPerTurn; }
int GetMaxMemory() const throw() {return m_MaxMemory; }
bool GetInfect() const throw() { return m_InfectOnAttack; }
void setPoint(Point p1, Point p2, Point p3)
{
point1=p1;
point2=p2;
point3=p3;
}
};
最佳答案
有两种方法可以到达这里。
首先:在 MachineState
的构造函数中,您必须设置一个变量,它确定该字段上的内容,并添加一个函数,它告诉您这一点。如果它的返回值为“0”,您就会知道该字段为空。
第二:声明一个二维指针数组。
MachineState *world[19][19];
memset(world, 0, sizeof(world));
这段小代码会将所有指针设置为 0 (NULL),然后您可以检查它。当然你需要手动为这个二维数组分配对象。
还有一点,您的 getWorld()
函数看起来有问题。
请考虑改用此功能:
MachineState *getField(MachineState state) {
return world[state.x][state.y];
}
或者,您当然可以使用:
MachineState *getField(int X, int Y) {
return world[X][Y];
}
后一个函数可以这样调用:
MachineState *Field = ZombieLand::getField(state.x, state.y - 1);
if(Field != NULL) state.m_occupied = true;
当然你需要添加边界检查,但这超出了这个答案的范围。
关于c++ - 检查二维数组中的对象是否为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16200131/