xcode 项目中的 typedef 枚举范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6543097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:23:37  来源:igfitidea点击:

typedef enum scope in xcode projects

objective-cxcode

提问by Daniel

So, my current understanding of enum is that I can use it to make constants that correspond to numbers. So,

所以,我目前对 enum 的理解是我可以用它来制作与数字相对应的常量。所以,

typedef enum 
{
    number0 = 0,
    number1 = 1,
    .
    .
    .

} Numbers;

would allow me to refer to 0 as number0 in every part of the code. This seems to work fine. However, I'm having trouble figuring out how to use this in an Xcode Project. For example, say I write one class, NumberCounter, and include this code in the header file. Then, I write another class, numberCalculator. If I want to use the same definitions in the second class, do I have to A) write the classes in the same source file, or B) include the above code in every file I want to use the numbers?

将允许我在代码的每个部分将 0 称为 number0。这似乎工作正常。但是,我无法弄清楚如何在 Xcode 项目中使用它。例如,假设我编写了一个类NumberCounter,并将此代码包含在头文件中。然后,我写了另一个类,numberCalculator. 如果我想在第二个类中使用相同的定义,我是否必须 A)在同一个源文件中编写类,或者 B)在我想使用数字的每个文件中包含上述代码?

If I include the code in one class, and exclude it in the second, I get (when trying to have a function return something of type Numbers) a Parse Issue Expected a Type error, but if I include the code in both, it gives an error about 'Redefinition of enumerator'. Currently, my workaround is to include the code in every file, then use the preprocessor to make sure it is only executed once - i.e:

如果我将代码包含在一个类中,并在第二个类中排除它,我会得到(当尝试让函数返回类型时Numbers)解析问题预期类型错误,但是如果我在两个类中都包含代码,它会给出关于“重新定义枚举器”的错误。目前,我的解决方法是将代码包含在每个文件中,然后使用预处理器确保它只执行一次 - 即:

#ifndef NumberDef
#define NumberDef
typedef enum 
{
    number0 = 0,
    number1 = 1,
    .
    .
    .

} Numbers;
#endif

This works, but I feel like there should be a nice simple way of doing this. What am I missing here?

这有效,但我觉得应该有一个很好的简单方法来做到这一点。我在这里错过了什么?

回答by tc.

Include the header it's defined in.

包括它在其中定义的标题。