代码之家  ›  专栏  ›  技术社区  ›  Malachi majid hussain

在C中传递枚举

  •  0
  • Malachi majid hussain  · 技术社区  · 15 年前

    这似乎是一个简单的问题,但我在编译它时遇到了一个错误。我希望能够将枚举传递到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 回复  |  直到 15 年前
        1
  •  5
  •   RichieHindle    15 年前

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

    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() 代码尚未看到类型。

        2
  •  -2
  •   pts    15 年前

    尝试改变

    p.type = type;
    

    p.type = (int)type;
    

    如果这不起作用,请添加整个.c文件,包括 struct Particle 回答你的问题。