记得适当的声明成员函数为const.

如果确信一个成员函数不用修改它的对象,就可以声明它为const,这样就可以作用于他的const对象了.因为const对象只能调用它的const方法.

 1 template<class T> class Vector
 2 {
 3 public:
 4     int length() const//如果这里没有const,那么该程序会运行失败,因为padded_length的方法中的参数是const的.
 5     {
 6         return 2;
 7     };
 8     int length(int);
 9 };
10 template<class T>
11 int padded_length(const Vector<T>&v,int n)
12 {
13     int k = v.length();
14     return k>n?k:n;
15 }
16 int main(int argc,char* argv[])
17 {
18     Vector<int> a;
19     cout<<padded_length(a,3)<<endl;
20     return 0;
21 }
原文地址:https://www.cnblogs.com/crazycodehzp/p/3902704.html