我遇到了非法访问错误的问题,我已经从 Player.h 中删除了默认构造函数,因为我推断问题是由它引起的。我现在遇到的问题是 Level.cpp 需要一个默认构造函数,所以我编辑了 Level.h 文件,如图所示。该问题已解决,但现在我无法将指针返回给玩家。正在显示错误“对绑定成员函数的非法操作”。请问有什么想法吗?我是 C++ 的初学者,任何帮助将不胜感激。
播放器.h:
#ifndef _TAG_PLAYER
#define _TAG_PLAYER
#pragma once
#include "Tile.h"
#include "Point.h"
class CGame;
class CPlayer : public CTile
{
public:
CPlayer(Point pos, CGame* game);
~CPlayer();
char getDisplay() ;
virtual bool canMove(const Direction direction, Point p) ;
virtual void move(const Direction direction, Point p);
bool CheckForHome() ;
};
#endif _TAG_PLAYER
播放器.cpp:
#include "Box.h"
#include "Level.h"
#include "Tile.h"
CPlayer::CPlayer(Point pos, CGame* game)
{
this->game=game;
Point p;
p.x=0;
p.y=0;
setPosition(p);
}
CPlayer::~CPlayer()
{
}
bool CPlayer::CheckForHome() {
Point p = getPosition();
bool OnHomeTile;
if(game->getLevel()->getTiles()[p.y][ p.x] == GOAL)
{
OnHomeTile = true;
} else {
OnHomeTile = false;
}
return OnHomeTile;
}
char CPlayer::getDisplay()
{
if (CheckForHome())
{
return SOKOBANONGOAL_CHAR;
}
else
{
return PLAYER_CHAR;
}
}
级别.h:
#pragma once
#include "Point.h"
#include "Tile.h"
#include "Player.h"
#include "Box.h"
#include <list>
#include <string>
class CGame;
class CLevel
{
private:
list<CBox> boxes;
TileType tiles[GRID_HEIGHT][GRID_WIDTH];
CPlayer player(Point p, CGame* game); -> new declaration
//CPlayer player; -> old declaration
protected:
CGame* game;
public:
CLevel();
~CLevel();
CPlayer* getPlayer();
list<CBox>* getBoxes();
TileType (*getTiles())[GRID_WIDTH];
};
Level.cpp 的构造函数
CLevel::CLevel()
{
this->game=game;
Point p;
p.x=0;
p.y=0;
player(p,game);
memset(tiles, GROUND, sizeof(TileType)*GRID_HEIGHT*GRID_WIDTH);
}
Level.cpp中有错误的函数:
CPlayer* CLevel::getPlayer()
{
return &player;
}