Re: [C++] Best Way to ++booleans?

From: Jeff Schwab (jeffplus_at_comcast.net)
Date: 01/24/04

  • Next message: diet.tonic_at_soda.club: "Re: cout on character array prints characters past end"
    Date: Sat, 24 Jan 2004 14:33:10 -0500
    
    

    entropy123 wrote:
    > Hey all,
    >
    > Not sure if the question is quite right, but I would like to do the following.
    >
    > Assign each node a color, say white.
    >
    > Something happens to a node so I want to change its color to grey.
    >
    > Another thing happens and I change its color to black.
    >
    > And so on for all the nodes in the system.
    >
    > I'd really like to do this as a 'boolean'.
    >
    > say...
    >
    > class Node() {
    >
    > bool IsBlack();
    > bool IsWhite();
    > bool IsGrey();
    >
    > private
    > int data;
    > <????> color;
    > }
    >
    >
    > Any suggestions as to how to pull this off?

    Martin's suggestion is good, and I believe it answers your question.
    Here's an approach I usually prefer.

    enum Color
    {
          black,
          white,
          gray
    };

    struct Node
    {
          Node( int data =0, Color color =white );

          Color const& color( );

    private:
          int m_data;
          Color m_color;
    };

    Node::Node( int data, Color color ):
          m_data( data ),
          m_color( color )
    {

    }

    Color const& Node::color( )
    {
          return m_color;
    }

    #include <iostream>

    int main( )
    {
          Node node;

          std::cout << "A default-constructed node is ";

          if( node.color( ) == black )
          {
               std::cout << "black.\n";
          }
          else if( node.color( ) == white )
          {
               std::cout << "white.\n";
          }
          else if( node.color( ) == gray )
          {
               std::cout << "gray.\n";
          }
          else
          {
               std::cout << "of unknown color.\n";
          }
    }


  • Next message: diet.tonic_at_soda.club: "Re: cout on character array prints characters past end"

    Relevant Pages