在 C++ 中使用关键字 class 作为变量名
我在编写使用为 C 文件设计的头文件的 C++ 代码时遇到问题。特别是,头文件使用了一个名为 class 的变量名:
int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs);
这在 C 中有效,因为 class 不被视为关键字,但在 C++ 中,class 是。那么我是否可以将这个头文件 #include 到 c++ 文件中,或者我运气不好?
谢谢。
I am having trouble writing C++ code that uses a header file designed for a C file. In particular, the header file used a variable name called class:
int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs);
This works in C as class isn't taken as a keyword, but in C++, class is. So is there anyway I can #include this header file into a c++ file, or am I out of luck?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试这样的事情:
它可能会导致问题,但也许值得一试
(使用 Makefile):
try something like this:
it may cause problems, but maybe worth a shot
alternative (using Makefile):
如果这只是声明,那么变量名称根本不重要。您可以完全删除它们或按照您的意愿更改它们。这是因为声明仅定义了函数的名称和类型,即:
但是如果您想要名称(更具描述性),您可以在所拥有的内容末尾添加下划线:
这不会'不要破坏任何其他代码。
If this is declaration only, then the variable names don't matter at all. You can completely remove them or change them how you please. This is because the declaration merely defines the name and type of the function, which is:
But if you want the names (to be a bit more descriptive), you can just throw an underscore at the end of what you have:
This won't break any other code.
您始终可以使用
#ifdef __cplusplus
在该标头中创建特定于 C++ 的声明You can always use
#ifdef __cplusplus
to create a declaration specific for C++ in that header您需要修改标头以将“class”替换为其他内容,以便将其编译为 C++。
You will need to modify the header to replace 'class' with something else in order to compile it as C++.
实际上,你运气不好。 “class”是一个保留字,您不能将其用作变量标识符。
我想你可以做一些预处理器技巧,比如
但实际上这也很愚蠢,因为它会让你的代码变得混乱并阻止你使用真正的类。
硬着头皮将参数重命名为“theclass”之类的。
As a practical matter, you're out of luck. "class" is a reserved word, you can't use it as a variable identifier.
I suppose you could do preprocessor tricks, like
But really that's silly, too, because it'll make your code confusing and prevent you from using real classes.
Just bite the bullet and rename the parameter 'theclass' or something.