const的一些注意事项
生活随笔
收集整理的這篇文章主要介紹了
const的一些注意事项
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天在繼續學習STL的過程中遇到了一些編譯錯誤??匆幌孪旅娴拇a——
class stone{private:int weight;public:stone(int i){weight=i;}bool operator<(const stone& st){return weight<st.weight;} };template<class T> inline bool min(const T& a,const T& b){return a<b?true:false; }int main(){stone a(1);stone b(2);cout<<::min(a,b); }代碼很簡單,是關于函數模板與重載的一個test,但是卻報了這樣的一個編譯錯誤[Error] passing ‘const stone’ as ‘this’ argument of ‘bool stone::operator<(const stone&)’ discards qualifiers [-fpermissive]
原因是我在寫模板時往往有這樣的一個編程習慣 inline bool min(const T& a,const T& b),如果T不是類的話沒有問題,但如果T是一個類的話,const修飾的對象只能訪問const函數,而我上面的重載函數卻恰恰沒有在參數列表后加上一個const,導致了這個錯誤。
所以干脆來總結一下const的注意事項吧——
型;
總結
以上是生活随笔為你收集整理的const的一些注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [力扣leetcode39]组合总和及回
- 下一篇: 中国电信实习