c++ 顶层const指针和底层const指针的解读技巧

画一条穿过*位置的垂直直线
如果const出现在线的左边,说明指针指向的数据为常量
如果const出现在线的右边,说明指针本身是常量
如果const在线的两边都出现,说明两者都是常量。

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //前面两句在c++11中是不允许的,其他情况下会抛出一个警告。
    char *p = "yami";                   //没有const
    char * const p2 = "yami";           //以*为分隔,const在右边,表明指针p2是const指针

    const char *p1 = "yami";            //以*为分隔,const在左边,表明指针p1所指向的数据为const
    const char * const p3 = "yami";     //以*为分隔,const在右边,表明指针p3是const指针,const也在左边,表明p3所指向的数据也是const

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36748278/article/details/80403870