【发布时间】:2013-11-29 02:57:35
【问题描述】:
使用以下代码(为简洁起见):
颜色.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: 错误:将 'const std::map >' 作为 'std::map<_key _tp _compare _alloc>::mapped_type& std::map::operator[](std::map<_key _tp _compare _alloc>::key_type&&) [with _Key = int; _Tp = std::basic_string; _比较 = 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 用于不修改数据的成员函数,所以我想知道如何处理这个问题。
我通常非常擅长调试/故障排除,但错误消息太复杂以至于没有多大帮助。
感谢任何帮助。
【问题讨论】:
-
我的第一个建议是适当地使用 std::map::find 调用删除 color::getColorText() const 中的下标运算符。