顶层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引用;
《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引用;
相关文章推荐
- Hive 安装及测试一
- 基于ajax实现点击加载更多无刷新载入到本页
- js在html中的加载执行顺序
- 深入剖析MongoDB架构
- Service和bindService生命周期
- Android快捷开关实现 Wifi开关、蓝牙开关、GPS开关、同步开关、亮度设置开关
- 自定义View之onMeasure()
- 位域
- NOR和NAND
- 总结子类父类的调用顺序
- 解析xml
- Debug Assertion Failed! FILE viewform.cpp , line 69
- Think in Java(Java编程思想)-第2章 一切都是对象
- 同步 异步 概念
- golang level
- 详解ASP.NET配置文件Web.config
- TCP/IP,http,socket,长连接,短连接
- oracle开启闪回
- centos5.4简单配置LVS-DR
- Java构造和解析Json数据的两种方法详解一