C++ “error: passing 'const std::map >' as 'this' argument of …”

后端 未结 3 1930
清酒与你
清酒与你 2020-12-03 18:02

With the following code (excerpted for brevity):

color.h:

class color {
public:
    color();

    enum colorType {
        black, blue, green, cyan,          


        
3条回答
  •  渐次进展
    2020-12-03 18:33

    string color::getColorText() const {
        return colors[cColortype];
    }
    

    The issue is that you've marked the function as const. The operator[] on std::map is marked as non-const, and cannot be used in a const function like this. You need to manually use std::map::find (or other mechanism) to search for the input type and handle the case where it's not found.

    If you're using C++11, you can instead use std::map::at, which IS allowed to be used on a constant map, and throws an exception if the requested element is not present.

提交回复
热议问题