how to make bool class with custom output?

Discussion in 'C++' started by bonham28c@gmail.com, Apr 2, 2006.

  1. Guest

    hi,
    i m trying to make a custom bool class.
    anything is the same as bool except when it is printing, i want it to
    print + if true and - if false.
    but it seems like i cant subclass bool like below:

    class regions: public bool
    {
    public:
    friend ostream& operator<<(ostream& ost, const bool& inRegions) {
    return inRegions ? "+" : "-";
    }

    };

    any suggestions?

    thanks for any help!
    , Apr 2, 2006
    #1
    1. Advertising

  2. wrote:
    > hi,
    > i m trying to make a custom bool class.
    > anything is the same as bool except when it is printing, i want it to
    > print + if true and - if false.
    > but it seems like i cant subclass bool like below:


    Precisely, primitive data types can't be inherited by classes.

    > any suggestions?

    Choose aggregation to inheritance.
    >
    > thanks for any help!
    >
    Aleksander Beluga, Apr 2, 2006
    #2
    1. Advertising

  3. Guest

    thanks!

    i think something like below will work too. i can also overload
    operator () to return true or false. but then in other functions, i
    cannot use if (region == true) { ....}
    any cleaner solution?

    class regions {
    public:
    friend ostream& operator<<(ostream& ost, const bool& inRegions) {
    if (inRegions) {
    return ost << "+" ;
    } else {
    return ost << "-" ;
    }

    bool mbool;
    };
    , Apr 2, 2006
    #3
  4. Guest

    i end up with the below code now. please feel free to make any
    suggestions for improvement. thanks a lot!

    class regions {
    public:
    regions() {}
    regions(const bool& inBool) {mbool=inBool;}

    friend bool operator== (const regions& a, const regions& b) {
    if (a.mbool==b.mbool) {return true;} else {return false;}
    }

    bool operator= (const bool& inbool) { mbool = inbool; return &mbool;
    }

    bool operator! (void) { return !mbool; }

    friend ostream& operator<<(ostream& ost, const regions& inRegions) {
    if (inRegions.mbool) {
    return ost << "+" ;
    } else {
    return ost << "-" ;
    }
    }

    bool mbool;
    };
    , Apr 2, 2006
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Pierre Espenan

    Returning bool from long integer class

    Pierre Espenan, Dec 26, 2003, in forum: C++
    Replies:
    3
    Views:
    1,694
    Pierre Espenan
    Dec 27, 2003
  2. Replies:
    1
    Views:
    302
  3. Joseph Turian
    Replies:
    10
    Views:
    780
  4. c4tech
    Replies:
    0
    Views:
    360
    c4tech
    Jul 1, 2009
  5. Christopher Pisz
    Replies:
    13
    Views:
    397
    Jorgen Grahn
    May 5, 2013
Loading...

Share This Page