Some good example for using enums

后端 未结 10 1618
感情败类
感情败类 2021-01-05 06:28

I learned enums when I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is d

10条回答
  •  清歌不尽
    2021-01-05 07:04

    One use of enums is to make code clearer at the call site. Compare:

    //Usage: Kick(Dog);
    
    enum PetType
    {
       Cat,
       Dog
    };
    
    void Kick(PetType p)
    {
       switch(p)
       {
          case Cat:
            //Kick Cat
            break;
          case Dog:
            //Kick Dog
            break;
          default:
            //Throw an exception.
            break;
        }
    }
    

    //Usage: Kick(false);
    
    void Kick(bool isCat)
    {
        if (isCat)
        {
            //Kick Cat
        }
        else
        {
            //Kick Dog
        }
    }
    

    Even though a boolean would work just as well, someone unfamiliar with the function will need to work much harder to determine what it does in the case that a boolean was used. Kick(Dog) is much clearer than Kick(false).

提交回复
热议问题