C++"错误:将'const std :: map <int,std :: basic_string <char >>>'作为'this'参数传递给......"

 为我有方 发布于 2023-02-13 20:41

使用以下代码(为简洁起见摘录):

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 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];
}

我收到以下错误:

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的建议对于不修改数据的成员函数,所以我想知道如何处理这个问题.

我通常擅长调试/故障排除,但错误信息是如此复杂,以至于它没有多大帮助.

任何帮助表示赞赏.

2 个回答
  • string color::getColorText() const {
        return colors[cColortype];
    }
    

    问题是你已将该功能标记为const.的operator[]std::map被标记为非const,并且不能在这样一个const函数一起使用.您需要手动使用std::map::find(或其他机制)来搜索输入类型并处理未找到的情况.

    如果您使用的是C++ 11,则可以改为使用std::map::at,允许在常量映射上使用,如果请求的元素不存在则抛出异常.

    2023-02-13 20:43 回答
  • 关键是接近尾声:"丢弃限定词".getColorText是一个const部件的功能,所以colorsconst.但map::operator[]()事实并非如此const.

    2023-02-13 20:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有