在C中传递枚举

时间:2009-04-30 22:16:26

标签: c types enums compiler-errors

这似乎是一个简单的问题,但我在编译时遇到错误。我希望能够将枚举传递给C中的方法。

枚举

enum TYPES { PHOTON, NEUTRINO, QUARK, PROTON, ELECTRON };

调用方法

makeParticle(PHOTON, 0.3f, 0.09f, location, colour);

方法

struct Particle makeParticle(enum TYPES type, float radius, float speed, struct Vector3 location, struct Vector3 colour)
{
    struct Particle p;
    p.type = type;
    p.radius = radius;
    p.speed = speed;
    p.location = location;
    p.colour = colour;

    return p;
}

我得到的错误是当我调用方法时:

  分配

中不兼容的类型

2 个答案:

答案 0 :(得分:5)

在这个缩减的例子中,它对我来说很好:

enum TYPES { PHOTON, NEUTRINO, QUARK, PROTON, ELECTRON };

void makeParticle(enum TYPES type)
{
}

int main(void)
{
    makeParticle(PHOTON);
}

您是否确定TYPES的定义中的代码可以使用makeParticle的声明以及对它的调用?如果你这样做,它将无法运作:

int main(void)
{
    makeParticle(PHOTON);
}

enum TYPES { PHOTON, NEUTRINO, QUARK, PROTON, ELECTRON };

void makeParticle(enum TYPES type)
{
}

因为main()代码尚未看到TYPES。

答案 1 :(得分:-2)

尝试更改

p.type = type;

p.type = (int)type;

如果这样做无效,请将整个.c文件添加到您的问题中,包括struct Particle的定义。