2

I have a simple class that uses an enum for "status". When I use the getStatus member function, it does indeed return "Busy" but when I print the value, it shows a "1". How can I print "Busy" instead of 1?

http://codepad.org/9NDlxxyU demonstration

#include <iostream>
using namespace std;

enum Status{Idle, Busy};
class text
{
public:
    void SetStatus(Status s);
    Status getStatus();
private:
    Status s;       
};
void text::SetStatus(Status s)
{
    this->s = s;
}
Status text::getStatus()
{
    return this->s;
}

int main()
{
    text myText;
    myText.SetStatus(Busy);
    cout << myText.getStatus() << endl; //outputs 1, should output "Busy"
}
dukevin
  • 22,384
  • 36
  • 82
  • 111
  • 4
    No, @Nicol, that's not a duplicate at all. The answer to that question is to call the enum's `ToString` method, which only .Net enums have, not native C++ enums. – Rob Kennedy Oct 27 '11 at 21:34
  • 1
    It is _not_ a duplicate. OP is not asking for an 'automatic' way for any enum. He wants to know _what should be done_ to get _this_ enum displayed as desired. – sehe Oct 27 '11 at 21:35

2 Answers2

4

A fully working edit is live here: http://ideone.com/WFo4g

Add:

std::ostream& operator<<(std::ostream& os, const Status status)
{
    switch (status)
    {
        case Idle: return os << "Idle";
        case Busy: return os << "Busy";
        default:   return os << "Status:" << status;
    }

    return os << "<error>";
}
sehe
  • 374,641
  • 47
  • 450
  • 633
2

You can't without further work. Busy is just an identifier that exists at compile time for your convenience. During compilation, the compiler replaces all occurencies of it with the real value 1.

To make it work like you want, you'll need an extra array or mapping from the enum value to a string that depicts the enum identifier.

Xeo
  • 129,499
  • 52
  • 291
  • 397