在 C 中传递枚举

发布于 2024-07-18 14:58:50 字数 629 浏览 1 评论 0原文

这似乎是一个简单的问题,但我在编译时遇到错误。 我希望能够将枚举传递到 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;
}

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

赋值中的类型不兼容

This may seem like a simple question but i am getting an error when compiling this. I want to be able to pass an enum into a method in C.

Enum

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

Calling the method

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

Method

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;
}

The error I am getting is when I am calling the method:

incompatible types in assignment

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽心 2024-07-25 14:58:50

在这个简化示例中,它对我来说编译得很好:

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

void makeParticle(enum TYPES type)
{
}

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

您确定已在 makeParticle 的定义和调用它吗? 如果您这样做,它将不起作用:

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

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

void makeParticle(enum TYPES type)
{
}

因为 main() 代码还没有看到 TYPES。

It compiles fine for me, in this cut-down example:

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

void makeParticle(enum TYPES type)
{
}

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

Are you sure that you've made the declaration of TYPES available to the code in both the definition of makeParticle and the call to it? It won't work if you do this:

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

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

void makeParticle(enum TYPES type)
{
}

because the main() code hasn't seen TYPES yet.

听,心雨的声音 2024-07-25 14:58:50

尝试更改

p.type = type;

p.type = (int)type;

如果这没有帮助,请将整个 .c 文件(包括 struct Particle 的定义)添加到您的问题中。

Try changing

p.type = type;

to

p.type = (int)type;

If this doesn't help, please add the whole .c file, including the definition of struct Particle to your question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文