C++ const 关键字修饰常量

// Example program
#include <iostream>
#include <string>
int main()
{
  char hello[] = "helloworld!";
  int tmp = 6;
  int other = 7;
  const int * a = &tmp;
  int * const b = &tmp;
  const int * const c = &tmp;
  std::cout<<*a<<'\t'<<*b<<'\t'<<*c<<std::endl;
  a = &other;
//   *a = 0; //error
//   b = &other; //error
  *b = 0;
//   c = &other; //error
//   *c = 0; //error
  std::cout<<*a<<'\t'<<*b<<'\t'<<*c<<std::endl;
  return 0;
}

输出

6	6	6
7	0	0

核心思想:const在 * 的左边,表示被指的变量是常量,不可改变, const在 * 的右边,表示指针本身是常量,指针的地址不可改变,如果左右都有,则指针的所指地址和该地址的值都不可改变。

posted on 2020-08-13 22:18  庭中核桃树  阅读(195)  评论(0编辑  收藏  举报

导航