With the following code (excerpted for brevity):
color.h:
class color {
public:
color();
enum colorType {
black, blue, green, cyan,
First : the map map<int, string> colors
must be a map from cColorType to string instead of int :
map<cColorType, string> colors
Second : As some people already answered : map::operator[]()
is not const
. The reason for that is that this operator returns a reference, which allows you to modify its value.
Let me suggest the following solution : You can create a second private attribute : the color in string format. Therefore you'll have 2 Get functions (one for each type of color), and one Set function (which will modify the 2 color attributes).
The key is near the end: "discards qualifiers". getColorText
is a const
member function, so colors
is const
. But map::operator[]()
is not const
.
string color::getColorText() const {
return colors[cColortype];
}
The issue is that you've marked the function as const
. The operator[]
on std::map
is marked as non-const, and cannot be used in a const function like this. You need to manually use std::map::find
(or other mechanism) to search for the input type and handle the case where it's not found.
If you're using C++11, you can instead use std::map::at
, which IS allowed to be used on a constant map, and throws an exception if the requested element is not present.