With the following code (excerpted for brevity):
color.h:
class color {
public:
color();
enum colorType {
black, blue, green, cyan, red,
magenta, brown, lightgray, nocolor
};
colorType getColorType();
void setColorType(colorType cColortype);
string getColorText() const;
private:
colorType cColortype = nocolor;
map<int, string> colors = {
{black, "black"},
{blue, "blue"},
{green, "green"},
{cyan, "cyan"},
{red, "red"},
{magenta, "magenta"},
{brown, "brown"},
{lightgray, "lightgray"},
{nocolor, "nocolor"}};
};
color.cpp:
color::color() {
}
color::colorType color::getColorType() {
return cColortype;
}
void color::setColorType(colorType cColortype) {
this->cColortype = cColortype;
}
string color::getColorText() const {
return colors[cColortype];
}
I get the following error:
color.cpp:16:29: error: passing 'const std::map >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = int; _Tp = std::basic_string; _Compare = std::less; _Alloc = std::allocator > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::basic_string; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive]
The error refers to "return colors[cColortype];" in getColorText.
I'm writing this for a class project and I can get it to work for the sake of the assignment by removing the const declaration in the getColorText signature but I'm trying to learn/adopt good practices and adhere to the recommendation to use const for member functions that don't modify data so I want to know how to deal with this going forward.
I'm usually really good at debugging/troubleshooting but the error message is so convoluted that it's not much help.
Any help is appreciated.
See Question&Answers more detail:
os