当前位置:
首页 >
const的一些注意事项
发布时间:2025/3/21
30
豆豆
生活随笔
收集整理的这篇文章主要介绍了
const的一些注意事项
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
今天在继续学习STL的过程中遇到了一些编译错误。看一下下面的代码——
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]组合总和及回
- 下一篇: 中国电信实习