C++ 编译报错discards qualifiers [-fpermissive]

声明了一个类

class Card

{

public:   

   Card(const string&);

   int m_value;    

   char m_suit;    

private:    

    const static map<char, int> m_map;

};

const map<char, int> Card::m_map=    

{        

        {'2', 2},

        {'3', 3},

        {'4', 4},

        {'5', 5},

        {'6', 6},

        {'7', 7},

        {'8', 8},

        {'9', 9},

        {'T', 10},

        {'J', 11},

        {'Q', 12},

        {'K', 13},  

       {'A', 14}  

   };

Card::Card( const string& p_cardVal)

{    

    //m_value = Card::m_map[(p_cardVal[0]];

    m_value = Card::m_map.at(p_cardVal[0]);

    m_suit = p_cardVal[1];

}

红线部分会报错,显示error: passing ‘const std::map<char, int>’ as ‘this’ argument discards qualifiers [-fpermissive]

查看CPP reference 可以知道,map的[],都是非const 的,而m_map是const的对象,于是会报错。(见http://blog.csdn.net/xidwong/article/details/52754514)

T& operator[]( const Key& key );(1)
T& operator[]( Key&& key ); (2)

在map的成员函数中,at成员函数

T& at( const Key& key );(1)
const T& at( const Key& key ) const;(2)
因此使用下面的at便可以解决这个编译错误。
原文地址:https://www.cnblogs.com/hipposinsilt/p/6378513.html