指針常量:指針本身是常量,指針的值不能改變
常量指針:指針指向的值是“常量”(打引號表示的是不能通過指針改變指向的值,這個層面的常量,不一定要真的指向常量)
上代碼和註釋:
#include<iostream>
using namespace std;
int main(){
const int a=1;// const int
int b=2,c=3;
//理解:可以從右往左讀,p is a,*表示"pointer to"
// 1,測試常量指針
const int *p1;// p is a pointer to int const,常量指針:指向常量的指針
p1=&b;// 不一定要指向常量
cout<<*p1<<endl;
*p1=1;//不能通過指針改變指向的值,但該值(非常量時)可以通過其他方式改變,如b=1
cout<<*p1<<endl;
// 2,測試指針常量
// p is const pointer to int,指針常量:指針本身是常量
int *const p3=&b; // 既然指針本身是常量,必須賦予初值
cout<<*p3<<endl;
p3=&c;// 指針爲常量,也就不能再賦值,即指向不能變(但是指向的對象是可變的)
cout<<*p3<<endl;
// 3,既是指針常量,又是常量指針
// 根據以上可知,該指針指向不能變,也不能通過該指針取修改指向的值(其他方式允許)
const int *const p4=&b;// p is const pointer to int const
b=6;// 可以通過其他方向改變指向的值
cout<<*p4<<endl;
// 4,其他寫法:int和const可以交換
// int const *p2;// p is a pointer to const int,so p2=p1
// int const *const p5;// p is const pointer to const int,so p5=p4
return 0;
}