|
-
September 25th, 2008, 04:26 AM
#1
enum to string function
I have this basic program:
Code:
enum Color {Black, White};
Color myColor = White;
std::cout << "My color is " << myColor << std::endl
with out put: "Mycolor is 1".
What I want is: "My color is White".
I'm having trouble implementing a function to do this. I can see several (3) solutions:
1. The best: Finding a way to overcharge the operator "<<" when applied on an "Color" object, to return a "string". I'm not sure at all how to do this.
2. Write a function which would basically be "String Color2String(Color)". This would allow me to simply write:
std::cout << "My color is " << Color2String(myColor) << std::endl
However, I am not really sure how to return the string item, without creating a memory leak. Would it be possible maybe to define it as a member of the string class, and write this?:
std::cout << "My color is " << String::Color2String(myColor) << std::endl
3. This solution would just consist in putting a string as function input parameter. I do not like this solution, because it would require a reprocess line of code (or more in case of multiple colors), as such:
Color2String(myString, myColor);
std::cout << "My color is " << myString << std::endl
The actual core of the function would be nothing more than a simple switch statement, but I'm having trouble declaring my function, and returning the result. Can I get some help please? Thank you for your time
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|