在Arduino中使用像类一样的结构

时间:2015-02-21 19:39:17

标签: c struct arduino

我正在尝试使用Arduino Structs作为我正在编写的程序的类的近似值。这需要包含自引用函数,考虑到Arduino编译器中允许和不允许的内容,这绝对是一场噩梦。

以下是我要做的一小部分内容:

gun.h


struct Gun {
    int id;
    int damage;
    int (* onFire)(struct * g);
};

gun_def.h


#include "gun.h"

extern Gun gunlist[];
extern Gun mygun;

Gun getGun(int id);

gun_def.cpp


#include "gun.h"
#include "gun_def.h"

int fire1(struct * g){
    return g->damage;
}
int fire2(struct * g){
    return g->id;
}

Gun gun1 = {00, 10, fire1};
Gun gun2 = {01, 20, fire2};
Gun gun3 = {02, 20, fire1};

Gun mygun = gun1;
Gun gunlist[3] = {gun1, gun2, gun3};

Gun getGun(int id){
    return gunlist[id];
}

正如您所看到的,我们的想法是在Gun结构的每个实例中都有一个函数指针,然后由一些外部函数调用它来执行枪的必要回调。

这个实现存在很多问题,我无法使用typedef,额外的头文件或移动定义来尝试克服Arduino编译的怪异。如果有更简单或更简单的方法,请告诉我。我需要为我试图实现的系统提供这种变量回调。

我目前得到的一些错误如下:

In file included from gun_def.cpp:1:
gun.h:5: error: expected identifier before '*' token
In file included from /gun_def.h:1,
                 from gun_def.cpp:2:
gun.h:2: error: redefinition of 'struct Gun'
gun.h:2: error: previous definition of 'struct Gun'
gun_def.cpp:4: error: expected primary-expression before 'struct'
gun_def.cpp:4: error: expected ',' or ';' before '{' token
gun_def.cpp:7: error: expected primary-expression before 'struct'
gun_def.cpp:7: error: expected ',' or ';' before '{' token
gun_def.cpp:11: error: invalid conversion from 'int' to 'int (*)(int*)'
gun_def.cpp:12: error: invalid conversion from 'int' to 'int (*)(int*)'
gun_def.cpp:13: error: invalid conversion from 'int' to 'int (*)(int*)'

1 个答案:

答案 0 :(得分:0)

  

你能告诉我typedef结构如何Foo {...} Foo;语法是   应该读?

简而言之,声明typedef T Foo;Foo定义为T类型的同义词;您的示例允许将声明编写为e。克。

Foo foo1;
Foo foo2;

- 如果没有typedef,名称Foo将不会表示类型,而只会表示结构标记,因此需要编写

struct Foo foo1;
struct Foo foo2;

注意:如果您来自C ++,可能会感到困惑,因为在没有Foo的情况下,可以使用typedef struct Foo Foo;作为类型名称。