CList 声明为const
我们在MSDN中可以看到CList的GetHead函数有2种返回类型:
TYPE& GetHead( );
TYPE GetHead( ) const;
解释是:
If the list is const, GetHead returns a copy of the element at the head of the list. This allows the function to be used only on the right side of an assignment statement and protects the list from modification.
If the list is not const, GetHead returns a reference to an element of the list. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.
我想问的是:
怎么样声明,list是const的?
list是const的有什么好处呢? CList声明
[解决办法]
后置const的方法, 需要const的对象才能调用
const CList a;
a.call_const_method();
[解决办法]
直接申请一个const变量意义并不大,因为你几乎什么都做不了。
但如果你写了一个函数,由调用者传一个变量进来,如果你只读不修改这个变量,就可以而且推荐申明为const类型,这是个标准做法。