为枚举类型赋值
enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.str="fine";
obj.opt="Yes"; // compiler error
}
如何将const char *
分配给opt?
enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.str="fine";
obj.opt="Yes"; // compiler error
}
How can assign const char *
to opt?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需执行
以下代码:
尝试将字符串文字(完全不同的类型)分配给枚举类型,C++ 不会自动为您转换该类型。
您必须手动执行此操作,我喜欢保留一组免费函数来使用我的枚举进行此类转换,即我将把我的枚举包装在命名空间中并提供一些用于使用它们的函数:
现在您可以do:
所以你可以看到,C++ 中的枚举可能不会为你提供其他语言中枚举的所有花哨功能。您必须自己手动转换内容。
Just do
This code:
attempts to assign a string literal (a completely different type) to an enum type, which C++ doesn't automagically convert for you.
You'll have to do this manually, I like to keep a set of free functions around for doing conversions like this with my enums, ie I'll wrap my enums in a namespace and provide some functions for working with them:
Now you can do:
So you can see, enums in C++ probably don't give you all the bells and whistles of enums in other languages. You'll have to manually convert things yourself.
因为枚举值不是字符串。这是正确的:
Because an enum value is not a string. This is correct :
枚举不是字符串,而只是值
Enums are not strings, but just values
你不能这样做。您将必须使用一些字符串比较并设置它。
You can't do this. You will have to use some string comparisons and set it.
在您的情况下,您可以“转换”枚举为
const char*
。您所需要的只是创建宏。例如:
#define ENUM_TO_CSTR(x) #x
进而:
obj.opt=ENUM_TO_CSTR(是)
。该宏会将您传递给它的所有内容转换为类似 C 的字符串。它不会转换变量值,而只会转换其名称!
int x = 10;计算<< ENUM_TO_CSTR(x) << endl;
将在屏幕上打印
x
(不是10
),所以要小心使用它!In your case you can "convert" enum to
const char*
. All what you need is to create macro.For example:
#define ENUM_TO_CSTR(x) #x
and then:
obj.opt=ENUM_TO_CSTR(Yes)
.This macro will convert everything you pass to it into C-like string. It won't convert variable value, but only its name!
int x = 10; cout << ENUM_TO_CSTR(x) << endl;
Will print
x
(not10
) on screen, so be careful using it!当您尝试分配“是”时,这意味着您正在尝试分配字符串值,而不是枚举选项中的枚举常量。而是使用语法:
尝试从 obj 打印 opt 的值:
您将得到输出 0,因为枚举索引从 0 开始。Yes 是 0,No 是 1。
When you try to assign "Yes" it means that you are trying to assign a string value and not the enum constant from the enum options. Instead use the syntax:
Try printing the value of opt from obj:
You will get the output as 0, since enum indices start from 0. Yes is 0 and No is 1.