[英]Different implementations of a C header file
如何向此头文件添加多个实现:
MoveAgent.h
#ifndef _GAMEAGENT_
#define _GAMEAGENT_
#include "Defs.h"
#include "GameModel.h"
MoveDirection takeDirection(GameState *gs);
#endif _GAMEAGENT_
MoveAgent.c:假设我有一个返回随机移动的实现
MoveDirection takeDirection(GameState *gs) {
MoveDirection dir = DIR_NONE;
while (dir == DIR_NONE) {
int index = arc4random() % gs->moves_total;
MoveDirection tempDir = gs->moves[index];
if (tempDir != oppDir(gs->car.direction)) {
dir = tempDir;
}
}
return dir;
}
具有该功能的多个实现的实用方法是什么?
正如您可能猜到的那样,我是一名Java程序员,正在尝试制作基本游戏来学习C,因此我尝试这样做来模拟Java界面。
有任何想法吗?
这可能会在深层跳得太多,但是:
您可能在指向函数的指针以及具有执行任务的不同名称的函数的多个实现之后。
extern MoveDirection (*takeDirection)(GameState *gs);
MoveDirection takeDirectionRandom(GameState *gs)
{
...
}
MoveDirection takeDirectionSpiral(GameState *gs)
{
...
}
#include "MoveAgent.h"
// Default move is random
MoveDirection (*takeDirection)(GameState *gs) = takeDirectionRandom;
void setRandomMover(void)
{
takeDirection = takeDirectionRandom;
}
void setSpiralMover(void)
{
takeDirection = takeDirectionSpiral;
}
void mover(GameState *gs)
{
...;
MoveDirection dir = takeDirection(gs);
...;
}
因此,在该行的某处,您可以调用其中一个setXxxxxMover()
函数,然后使用由所调用的两个函数中的最后一个设置的机制进行移动。
您也可以使用长手记法调用该函数:
MoveDirection dir = (*takeDirection)(gs);
很久以前(20世纪80年代和更早),这种符号是必要的。 我仍然喜欢它,因为它清楚(对我来说)它是一个正在使用的指向函数的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.