使用以下代码(为简洁起见摘录):
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; mapcolors = { {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]; }
我收到以下错误:
color.cpp:16:29:错误:将'const std :: map>'作为'this'参数传递给'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]'丢弃限定符[-fpermissive]
错误是指"返回颜色[cColortype];" 在getColorText中.
我正在为一个类项目编写这个,我可以通过删除getColorText签名中的const声明来使其工作,但我正在尝试学习/采用良好实践并坚持使用const的建议对于不修改数据的成员函数,所以我想知道如何处理这个问题.
我通常擅长调试/故障排除,但错误信息是如此复杂,以至于它没有多大帮助.
任何帮助表示赞赏.
string color::getColorText() const { return colors[cColortype]; }
问题是你已将该功能标记为const
.的operator[]
上std::map
被标记为非const,并且不能在这样一个const函数一起使用.您需要手动使用std::map::find
(或其他机制)来搜索输入类型并处理未找到的情况.
如果您使用的是C++ 11,则可以改为使用std::map::at
,允许在常量映射上使用,如果请求的元素不存在则抛出异常.
关键是接近尾声:"丢弃限定词".getColorText
是一个const
部件的功能,所以colors
是const
.但map::operator[]()
事实并非如此const
.