Creating a Class for Enums

I'm new to learning C++ and I'm running into a bit of trouble. The book I'm learning from gives the following code, but it's not very specific when it describes the code.

1. #include
2. #include
4. using namespace std;
6. class Colors
7. {
8. public:
9. enum ColorEnum {blue, red, green, yellow, black};
10. Colors(Colors::ColorEnum value);
11. string AsString();
13. protected:
14. ColorEnum value;
15. };
17. Colors::Colors(Colors::ColorEnum initvalue)
18. {
19. value = initvalue;
20. }
22. string Colors::AsString()
23. {
24. switch (value)
25. {
26. case blue:
27. return "blue";
28. case red:
29. return "red";
30. case green:
31. return "green";
32. case yellow:
33. return "yellow";
34. case black:
35. return "black";
36. default:
37. return "Not Found";
38. }
39. }
41. int main()
42. {
43. Colors InkColor = Colors::red;
44. cout << InkColor.AsString() << endl;
45. return 0;
46. }

I understand how classes work for the most part and how switches work, but the code itself is confusing. In particular I have no idea why lines 10, 11, 17, or 22 are written the way they are.

Line 10
I don't understand why the Colors::ColorEnum value is inside the parenthesis with another Colors outside.

Line 11
I don't know how the value that is used by the switch later on is saved to AsString()

Line 17
Once again, I'm confused by the use of parenthesis. I think this is the function described in line 10 so I guess if someone explains why line 10 is written that way this line will make sense as well.

Line 22
I'm struggling to see where the value that's being tested by switch is found in AsString()

I know this isn't the complete code, but merely the code necessary for the computer to print the actual color instead of a number when cout << InkColor.AsString() << endl; is called, but I really don't understand how it all goes together.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!