The usage of const

const is a complie time constraint that an object can not be modified.

  const int i = 0;

  i = 9 ; // error

  const int *pi = &i; // data is const, pointer is not const.

  p1++; // complies, runs ok

  int* const p2; //pointer is const, data is not const

  const int* const p3; // data and pointer are both const

if const is on the left of the *, data is const; 

if const is on the right of the *, pointer is const.

    so const int *p4 = &i; equals to int const *p4 = &i;

switch between the const and non-const.

  const int i = 9;

  const_cast<int&>(i) = 6; // i is modified from const to non-const.

  int j;

  static_cast<const int&>(j) = 7;//j is modified from non-const to const.

猜你喜欢

转载自www.cnblogs.com/yunpengk/p/12954755.html
今日推荐