混合 Objective-C 和 C++ 代码
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
#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 :(
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
#undef
fing 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?