how to make bool class with custom output?

B

bonham28c

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!
 
A

Aleksander Beluga

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.
 
B

bonham28c

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;
};
 
B

bonham28c

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;
};
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top