how do I use an enum value on a switch statement in C++

后端 未结 8 1327
独厮守ぢ
独厮守ぢ 2020-12-02 20:16

I would like to use an enum value for a switch statement. Is it possible to use the enum values enclosed in \"{}\" as cho

8条回答
  •  广开言路
    2020-12-02 20:29

    • Note: I do know that this doesn't answer this specific question. But it is a question that people come to via a search engine. So i'm posting this here believing it will help those users.

    You should keep in mind that if you are accessing class-wide enum from another function even if it is a friend, you need to provide values with a class name:

    class PlayingCard
    {
    private:
      enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
      int rank;
      Suit suit;
      friend std::ostream& operator<< (std::ostream& os, const PlayingCard &pc);
    };
    
    std::ostream& operator<< (std::ostream& os, const PlayingCard &pc)
    {
      // output the rank ...
    
      switch(pc.suit)
      {
        case PlayingCard::HEARTS:
          os << 'h';
          break;
        case PlayingCard::DIAMONDS:
          os << 'd';
          break;
        case PlayingCard::CLUBS:
          os << 'c';
          break;
        case PlayingCard::SPADES:
          os << 's';
          break;
      }
      return os;
    }
    

    Note how it is PlayingCard::HEARTS and not just HEARTS.

提交回复
热议问题