【问题标题】:How to use Enum with strings in a function?如何在函数中使用 Enum 和字符串?
【发布时间】:2010-06-22 16:15:02
【问题描述】:

基本上,我有一个链接列表,它实现了一个display()函数,它简单地循环遍历元素并打印出它们的值。

我想这样做:

void List::display( std::string type )
{
    switch(type)
    {
      // Do stuff...

编译器立即抱怨。我的老师说这是因为在编译时字符串是未知的,导致错误。这个解释听起来有点可疑,但他建议我使用枚举。所以我研究了它,它说枚举的显式字符串不起作用。类似的东西

class List
{
    enum type 
    {
        HORIZONTAL = "inline"
        VERTICAL   = "normal"
    }

然后,我真的不知道。

enum type 是 List 类的一部分,也是函数 display() 的一部分。这再次看起来像一个非常糟糕的解决方案。不过,我想知道这种方法是否可行。

如何在调用 display() 的同时在 main 函数中设置枚举?像这样

int main( void )
{
    display("normal");

当然,更简单的方法是非常受欢迎的。一般来说,如果可能的话,我如何声明/将枚举传递给函数?

【问题讨论】:

    标签: c++ string class enums


    【解决方案1】:

    在当前 C++ 中,Switch 仅适用于整数类型。您可以定义您的枚举,打开它,并编写一个辅助函数,将枚举映射到字符串值(如果需要)。

    例子

    enum E { A, B };
    
    string E_to_string( E e )
    {
      switch(e)
      {
        case A: return "apple";
        case B: return "banana";
      }
    }
    
    void display( E e )
    {
      std::cout << "displaying an " << E_to_string(e) << std::endl;
      switch(e)
      {
        case A: // stuff displaying A;
        case B: // stuff displaying B;
      }
    }
    

    【讨论】:

      【解决方案2】:
      class List
      {
          enum Type
          {
              HORIZONTAL,
              VERTICAL
          };
      
          void display(Type type)
          {
              switch (type)
              {
                  //do stuff
              }
          }
      };
      
      int main()
      {
          List l;
          l.display(List::HORIZONTAL);
      }
      

      【讨论】:

      • 那是巫术!很酷,不知道你可以这样。谢谢!
      • Type 是否需要公开才能用作display 的参数?
      • 不,但如果您将其设为私有,则无法在main 中访问它,因此您无法从那里调用display
      猜你喜欢
      • 2017-03-04
      • 1970-01-01
      • 2011-01-18
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2012-05-18
      • 2014-11-19
      相关资源
      最近更新 更多