问题描述
我正在用C实现纸牌游戏.纸牌类型很多,每种都有很多信息,包括一些需要单独编写与之相关联的动作.
I'm implementing a card game in C. There are lots of types of cards and each has a bunch of information, including some actions that will need to be individually scripted associated with it.
给出这样的结构(我不确定我是否对函数指针具有正确的语法)
Given a struct like this (and I'm not certain I have the syntax right for the function pointer)
struct CARD {
int value;
int cost;
// This is a pointer to a function that carries out actions unique
// to this card
int (*do_actions) (struct GAME_STATE *state, int choice1, int choice2);
};
我想初始化一个静态数组,每张卡一个.我猜这看起来像这样
I would like to initialize a static array of these, one for each card. I'm guessing this would look something like this
int do_card0(struct GAME_STATE *state, int choice1, int choice2)
{
// Operate on state here
}
int do_card1(struct GAME_STATE *state, int choice1, int choice2)
{
// Operate on state here
}
extern static struct cardDefinitions[] = {
{0, 1, do_card0},
{1, 3, do_card1}
};
-
这项工作是否可行,我是否正以正确的方式进行处理?我正在努力避免大量的switch语句.
Will this work, and am I going about this the right way at all? I'm trying to avoid huge numbers of switch statements.
我是否需要提前定义'do_cardN'函数,或者在结构初始化中是否有某种内联定义它们的方法(类似于python中的lambda函数)?
Do I need to define the 'do_cardN' functions ahead of time, or is there some way to define them inline in the initialization of the struct (something like a lambda function in python)?
我需要对其他文件中的cardDefinitions进行只读访问-外部静态"是否正确?
I'll need read-only access to cardDefinitions from a different file - is 'extern static' correct for that?
我知道这是很多问题,但是我对于如何解决这个问题确实有点含糊.
I know this is a lot of questions rolled into one but I'm really a bit vague about how to go about this.
谢谢.
要清楚,我的目标是能够做类似的事情
To be clear, my goal is to be able to do something like
int cost = cardDefinitions[cardNumber].cost;
或
int result = cardDefinitions[cardNumber].do_action(state, choice1, choice2);
而不是到处使用巨大的switch语句.
Instead of using huge switch statements all over the place.
推荐答案
您的方法完全正确.
- 这将起作用,并且是避免庞大的
switch
语句的好方法. - 您不能在C语言中内联定义函数,每个函数必须具有唯一的名称.
-
extern
是您想要的,而不是static
.更改您的身体为:
- This will work, and is a good way to avoid huge
switch
statements. - You can't define functions inline in C, they each must have a unique name.
extern
is what you want, notstatic
. Change your body to be this:
struct CARD cardDefinitions[] = {
{0, 1, do_card0},
{1, 3, do_card1}
};
然后在适当的头文件中:
then in an appropriate header file:
extern struct CARD cardDefinitions[];
这篇关于在C中初始化结构的静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!