const 加 pointer,常量指针与指针常量的区别

 int * const p 和 const int * p;这两者哪个是常量指针哪个是指针常量,实在是容易搞混;
 按照英文原文,感觉好理解点:
 int * const p  --->  const pointer; 称为常量指针,应该没问题;或者就按英文来记;
 const int * p  --->  pointer to const; 称为 指向常量的指针, 虽然字数多,可好理解。。。

1. effictive c++ 条款 3 中: 如果关键字出现在星号(*)左边, 表示被指物是常量;
    如果出现在星号右边,表示指针自身是常量;
    如果出现在星号两边,表示被指物和指针两者都是常量;

2. primer C++中, 建议 从右往左读, 碰到变量名后,遇到const为常量,遇到 星号(*)为指针,
 这样:
 int * const p   读作  常量指针, 指针是常量,不可变;
 const int * p 或者 int const * p  读作 指针常量 , 指针所指物是常量,不可变;
 常量指针,指针常量,太容易搞混了,还是记作 const pointer, pointer to const吧,
 起码字数不一样,分得开。。。

      int x;
      int *       p1 = &x;  // non-const pointer to non-const int
      const int *       p2 = &x;  // non-const pointer to const int
      int * const p3 = &x;  // const pointer to non-const int
      const int * const p4 = &x;  // const pointer to const int 
发布了69 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u010096608/article/details/103205635