您的位置:首页 > 其它

顶层const和底层const

2015-10-16 09:49 393 查看
转载请注明出处!!

《C++ primer》 (第五版)P57关于顶层const和底层const有部分介绍。

原版中是这样描述的:

2.4.3.Top-Level const

  As we’ve seen, a pointer is an object that can point to a different object. As a result,we can talk independently about whether a pointer is const and whether the objects to
which it can point are const. We use the term top-level const to indicate that the pointer itself is a const. When a pointer can point to a const object, we refer to that const as a low-level const.
知乎上有人给出了很好的解释:

查看原文

1. const type FOO;           //常量

2. class Bar{
void foo_bar() const; 

};

const member function: 不允许改变member variable.

上述情况应该区别:

const   type   fun2(   );   

const   type*   fun3(   ); 

const在函数修饰函数的返回值,是对函数值的限定和修饰。

3. const type * ptr;          //指针所指向的variable不可改变---底层const

4. type * const ptr;          //pointer的值不可改变---顶层const

5. pass value by const reference: void foo (const &bar);  //function 不可改变bar的值。

使用const的建议:(转)

  1、要大胆的使用const,这将给你带来无尽的益处,但前提是你必须搞清楚原委;   

  2、要避免最一般的赋值操作错误,如将const变量赋值;   

  3、在参数中使用const应该使用引用或指针,而不是一般的对象实例,原因同上;   

  4、const在成员函数中的用法要很好的使用;   

  5、不要轻易的将函数的返回值类型定为const;   

  6、除了重载操作符外一般不要将返回值类型定为对某个对象的const引用;  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: