混合 Objective-C 和 C++ 代码

发布于 2024-08-01 14:08:01 字数 345 浏览 4 评论 0原文

我有一个 Objective-C/C++ 应用程序,它使用 C++ 库提供的功能。

其中一个 C++ 类包含这样的枚举:

class TheClass
{
public:
[...]

enum TheEnum
{
    YES,
    NO,
};

[...]
};

在 Objective-C/C++ 源文件 (*.mm) 中包含(使用 #import -如果这很重要-)具有上述类声明的头文件将使编译失败,因为预处理器将用术语“(BOOL) 1”替换“YES”(同样,用“(BOOL) 0”替换“NO”)。

有没有办法在不重命名枚举值的情况下解决这个问题?

I have an Objective-C/C++ application which uses functionality that is provided by a C++ library.

One of the C++ classes includes an enum like this:

class TheClass
{
public:
[...]

enum TheEnum
{
    YES,
    NO,
};

[...]
};

Including (using #import -if that matters-) a header file with the above class declaration in an Objective-C/C++ source file (*.mm) will make the compile fail since the preprocessor will replace "YES" by the term "(BOOL) 1" (and likewise "NO" by "(BOOL) 0").

Is there a way to fix that without renaming the values of the enum?

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

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

发布评论

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

评论(2

再浓的妆也掩不了殇 2024-08-08 14:08:01

#import 确实很重要——Objective-C++ 源文件中的 C++ 标头应该包含在 #include 中。 我认为,虽然不是 100% 确定,但包含指令(#include vs #import)的选择决定了使用哪个预处理器。

您还可以反转枚举中常量的声明,因为默认情况下,枚举的成员与从 0 开始的整数相关联。

根据评论,我错了。 看起来你必须重写枚举。 对不起 :(

The #import does matter -- C++ headers in an Objective-C++ source file should be included with #include. I think, though am not 100% sure, that the choice of include directive (#include vs #import) determines which preprocessor is used.

You could also reverse the declaration of the constants in the enum, since by default, members of an enum are associated with integers starting from 0.

Per comments, I'm wrong. Looks like you'll have to rewrite the enum. Sorry :(

叹梦 2024-08-08 14:08:01

YES 和 NO 是 Objective-C 中预定义的常量 ,在 objc.h 标头中声明。

您应该能够阻止预处理器扩展“YES”和“NO”宏。 这可以通过本地 #undef找到他们。

但从技术上讲,如果您使用语言关键字作为标识符,则可能会遇到麻烦。 您不会编写一个包含名为 MAX_PATH 的成员的类,对吗?

YES and NO are predefined constants in Objective-C, declared in the objc.h header.

You should be able to prevent the preprocessor to expand the "YES" and "NO" macro's. This can be done by locally #undeffing them.

But technically, if you're using a language keyword as an identifier, you can expect trouble. You won't write a class containing a member called MAX_PATH, would you?

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