如何在函数中使用带有字符串的 Enum?
基本上,我有一个链接列表,它实现了一个 display()
函数,该函数简单地循环遍历元素并打印出它们的值。
我想这样做:
void List::display( std::string type )
{
switch(type)
{
// Do stuff...
编译器立即抱怨。我的老师说这是因为该字符串在编译时未知,从而导致错误。这个解释听起来有点可疑,但他建议我使用枚举。所以我研究了它,它说显式枚举字符串不起作用。然后
class List
{
enum type
{
HORIZONTAL = "inline"
VERTICAL = "normal"
}
,我真的不知道。
枚举类型
是List类的一部分,也是函数display()
的一部分。这看起来又是一个非常蹩脚的解决方案。尽管如此,我想知道这种方法是否可行。
如何在调用 display() 的同时在主函数中设置枚举?当然
int main( void )
{
display("normal");
,更简单的方法是非常受欢迎的。一般来说,如果可能的话,如何声明/传递枚举给函数?
Basically, I have a Linked List which implements a display()
function that simply loops throught he elements and prints out their values.
I wanted to do it like this:
void List::display( std::string type )
{
switch(type)
{
// Do stuff...
The compiler immediately complained. My teacher said this would be because the string is not known at compile-time, resulting in an error. That explanation sounds a little iffy, but he suggested that I use enums. So I researched it and it says that explicit string to enums doesn't work. Something like
class List
{
enum type
{
HORIZONTAL = "inline"
VERTICAL = "normal"
}
and then, I really don't know.
The enum type
is a part of the List class, as well as the function display()
. This again looks like a really crappy solution. Nevertheless, I want to know if this approach is possible.
How could I set the enum in the main function at the same time I call display()? Like so
int main( void )
{
display("normal");
Of course, easier approaches are very welcome. In general, how do I declare/pass an enum to a function, if possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Switch 在当前的 C++ 中仅适用于整型。您可以定义枚举,打开它,并编写一个辅助函数,将枚举映射到字符串值(如果需要)。
例子
Switch, in current C++, only works with integral types. You could define your enum, switch on it, and write an auxiliary function that maps the enum to string values if needed.
Example