是否可以同时初始化需要相互指向指针的两个类? [英] Is it possible to initialise two classes, that require pointers to each other, at the same time?
问题描述
我正在做蛇游戏.我有两个类, snake
和 food
.当我调用 snake-> move()
时,它需要检查是否没有碰撞,为此,它需要知道 food
的位置,因此需要指向 food
的指针. food
具有将其移动到新的随机位置的功能,即 move-> setNewPosition()
,该功能需要知道 snake
的位置这样它在移动时不会与蛇碰撞.为此,它需要一个指向 snake
的指针.
I am making a snake game. I have two classes, snake
and food
. When I call snake->move()
it needs to check that there are no collisions and for this purpose it needs to know what food
's position is and therefore requires a pointer to food
. food
has a function that moves it to a new random position, move->setNewPosition()
, which needs to know the position of snake
so that it doesn't collide with the snake when it moves. For this purpose, it requires a pointer to snake
.
因此,对于这两个类,我都需要提供一个指向必须初始化的其他类的指针.但是要初始化另一个类,我需要初始化另一个类,依此类推.有什么方法可以初始化两个同时需要彼此指向指针的类?
Therefore, for both classes, I would need to supply a pointer to the other class which must be initialised. But to initialise the other class I need to initialise the other class and so on. Is there any way to initialise two classes, that require pointers to each other, at the same time?
如果没有,那么构造我的程序的更好方法是什么,它可以让我检查另一个类的坐标?
If not, what would be a better way of structuring my program that would allow me to check the coordinates of the other class?
推荐答案
如果我没有误解您,请创建在游戏循环开始之前调用的 init
函数:
If i don't misunderstand you, create init
function that call before game loop starts:
void initSnake()
{
auto snake = new Snake();
auto food = new Food();
snake->setFood(food);
food->setSnake(snake);
}
这篇关于是否可以同时初始化需要相互指向指针的两个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!