const之被指物是常量or指针是常量

演示代码为,

#include 

using namespace std;

int main() {
    char a[] = "hello!";
    char b[] = "world!";
    
    //====case1
    const char* p1 = a; //const在*之前,表示被指物是常量
    p1[0] = 'c'; //被指物是常量,不能通过指针p1修改,报错
    
    //====case2
    char const* p2 = a; //const在*之前,表示被指物是常量
    p2[0] = 'c'; //被指物是常量,不能通过指针p2修改,报错
    
    //====case3
    char* const p3 = a; //const在*之后,表示指针是常量
    p3 = b; //指针是常量,不能指向其它对象,报错
    
    return 0;
}

输出为,

a.cpp: In function 'int main()':
a.cpp:11:11: error: assignment of read-only location '* p1'
   11 |     p1[0] = 'c'; //被指物是常量,不能通过指针p1修改,报错
      |     ~~~~~~^~~~~
a.cpp:15:11: error: assignment of read-only location '* p2'
   15 |     p2[0] = 'c'; //被指物是常量,不能通过指针p2修改,报错
      |     ~~~~~~^~~~~
a.cpp:19:8: error: assignment of read-only variable 'p3'
   19 |     p3 = b; //指针是常量,不能指向其它对象,报错
      |     ~~~^~~

你可能感兴趣的:(C++学习,算法,c++)