1. const可被施加于任何作用域内的对象,函数参数,函数返回类型,成员函数本体.用const修饰指针,如果const出现在*之前,表明指针不能更改所指向的对象的内容,如果const出现在*之后,表明指针只能指向同一块内存.另外int const*p和const int*p含义相同.如果对象成员有普通指针,那么构造该类的一个const对象时,const修饰使得该指针只能指向同一块内存,但指针指向的内容可以改变.

2. 将某些东西声明为const可以帮助编译器侦测出错误用法.

3. 编译器强制实行bitwise constness(又称physical constness,物理上的常量性,即成员函数不更改对象的任何一个bit时才可以说是const),例如:

class TextBlock{
public:
    ...
    char& operator [](std::size_t position) const{
        return pText[position];
    }
private:
    char* pText;
}
View Code

相关文章:

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