以下是摘自代码的片段:
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"}};
};
颜色.cpp:
color::color() {
}
color::colorType color::getColorType() {
return cColortype;
}
void color::setColorType(colorType cColortype) {
this->cColortype = cColortype;
}
string color::getColorText() const {
return colors[cColortype];
}
我遇到了以下错误:
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]
在 getColorText 中的 "return colors[cColortype];" 导致了这个错误。
这是一个课程项目,为了完成作业,我可以通过移除 getColorText 签名中的 const 声明使其工作,但我想学习/采用良好的做法并遵循对不修改数据的成员函数使用 const 的建议,所以我想知道如何解决这个问题。
我通常非常擅长调试和故障排除,但是这个错误消息太复杂了,几乎没有什么帮助。
感谢任何帮助。