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便可以解決這個編譯錯誤。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM