[英]C++ friend class invalid use of incomplete type OOP
I have decided learn some OOP and I started get rid of conditionals (I know in this program this in unnecessary but I have to start with simply example). 我决定学习一些OOP,并开始摆脱条件(我在程序中知道这是不必要的,但我必须从简单的示例开始)。
In class DirectConditions
, I have my conditions and I would pass object of SnakeGame
by reference to friend class DirectConditions
's method and change value of some variables of SnakeGame
in DirectConditions
's method. 在课堂上DirectConditions
,我有我的条件,我会通过的对象SnakeGame
参考友元类DirectConditions
的方法和一些变量的变化值SnakeGame
在DirectConditions
的方法。
Error : 错误 :
invalid use of incomplite type 'class DirectConditions::SnakeGame' snakeObj.snake[0].xCoor+=1;
Another Question : 另一个问题 :
May I take this occasion to ask: this way to get rid of conditionals(if's) is good? 我可以借此机会问一下:这种摆脱条件限制的方法是好的吗? I would really appreciate help. 我非常感谢您的帮助。
Providing the code: 提供代码:
snakeGame.hpp : snakeGame.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
directConditions.hpp : directConditions.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
You should avoid including of headers by each other - that's why you're getting "invalid use of incomplete type". 您应该避免彼此包含标头-这就是为什么您会得到“无效使用不完整类型”的原因。 Change those includes to forward declarations and move implementation of methods to cpp files. 更改这些内容以转发声明并将方法的实现移至cpp文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.