Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5428
Number of posts: 16949

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Creating a Class for Enums Posted by Xanatos57 on 28 Sept 2012 at 11:07 AM
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 <iostream>
2. #include <string>
3.
4. using namespace std;
5.
6. class Colors
7. {
8. public:
9. enum ColorEnum {blue, red, green, yellow, black};
10. Colors(Colors::ColorEnum value);
11. string AsString();
12.
13. protected:
14. ColorEnum value;
15. };
16.
17. Colors::Colors(Colors::ColorEnum initvalue)
18. {
19. value = initvalue;
20. }
21.
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. }
40.
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.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.