一、const表示被指之物是常量

C++primer 第二章

条款03:尽可能使用const

 

二、const与函数声明

 

函数返回一个常量值,往往可以降低因客户错误而造成的意外:

 

条款03:尽可能使用const

条款03:尽可能使用const

 

 

三、const成员函数

条款03:尽可能使用const

条款03:尽可能使用const

但是,顶层const会被忽略,所以顶层const不会重载。见《C++primer》 P191

条款03:尽可能使用const

条款03:尽可能使用const

 

mutable:

条款03:尽可能使用const

 

四、const和non-const成员函数中避免重复

条款03:尽可能使用const

 

条款03:尽可能使用const

运用const成员函数实现出其non-const孪生兄弟:

条款03:尽可能使用const

 

 

反过来是不行的:

条款03:尽可能使用const

 

 

总结:

1、将某些东西声明为 const可帮助编译器侦测出错误用法。 const可被施加于任何作用域内的对象、函数参数、函数返回类型、成员函数本体。
2、编译器强制实施 bitwise constness,但你编写程序时应该使用“概念上的常量性”(conceptual constness)

3、当 const和non- const成员函数有着实质等价的实现时,令non- const版本调用 const版本可避免代码重复

 

相关文章:

  • 2021-09-08
  • 2021-11-16
  • 2022-02-23
  • 2021-09-20
  • 2021-10-13
  • 2021-07-19
  • 2022-02-15
猜你喜欢
  • 2022-01-24
  • 2021-07-14
  • 2022-12-23
  • 2021-10-09
  • 2021-06-01
  • 2022-12-23
相关资源
相似解决方案