我决定学习一些 OOP 并开始摆脱条件(我知道在这个程序中这是不必要的,但我必须从简单的例子开始)。
在 classDirectConditions
中,我有我的条件,我会通过SnakeGame
引用朋友 class的方法传递 object 并更改in方法DirectConditions
的某些变量的值。SnakeGame
DirectConditions
错误:
invalid use of incomplite type 'class DirectConditions::SnakeGame' snakeObj.snake[0].xCoor+=1;
另一个问题:
我可以借此机会问一下:这种摆脱条件(如果)的方式好吗?我真的很感激帮助。
提供代码:
蛇游戏.hpp:
#ifndef _SNAKEGAME_HPP
#define _SNAKEGAME_HPP
#include<string>
#include"directConditions.hpp"
#include<map>
class SnakeGame{
public:
SnakeGame();
void mainLogic();
void check();
friend class DirectConditions;
private:
const int width,height;
int sizeOfSnake;
std::string direction;
std::map<std::string,DirectConditions*> directMap;
struct Snake{ int xCoor,yCoor; }snake[100];
enum Directions{up,down,left,right} directEnum;
void initializeMap();
};
SnakeGame::SnakeGame():width(500),height(500),sizeOfSnake(3){}
void SnakeGame::check(){
for(int i=sizeOfSnake;i>0;--i){
snake[i].xCoor=snake[i-1].xCoor;
snake[i].yCoor=snake[i-1].yCoor;
}
directMap[direction].goToDirection(this);
}
//private fun
void SnakeGame::initializeMap(){
directMap["right"]=new GoRight;
directMap["left"]=new GoLeft;
directMap["up"]=new GoUp;
directMap["down"]=new GoDown;
}
#endif
直接条件.hpp:
#ifndef _DIRECTCONDITIONALS_HPP
#define _DIRECTCONDITIONALS_HPP
#include"snakeGame.hpp"
class DirectConditions{
public:
class SnakeGame;
virtual void goToDirection(SnakeGame&)=0;
virtual ~DirectConditions(){};
};
class GoRight:public DirectConditions{
public:
void goToDirection(SnakeGame& snakeObj){
snakeObj.snake[0].xCoor+=1;
}
};
class GoLeft:public DirectConditions{
public:
void goToDirection(SnakeGame& snakeObj){
snakeObj.snake[0].xCoor-=1;
}
};
class GoUp:public DirectConditions{
public:
void goToDirection(SnakeGame& snakeObj){
snakeObj.snake[0].yCoor+=1;
}
};
class GoDown:public DirectConditions{
public:
void goToDirection(SnakeGame& snakeObj){
snakeObj.snake[0].yCoor-=1;
}
};
#endif