#include <iostream>
using namespace std;
int main()
{
int B1=1,B2=2,B3=3,B4=4,B5=5;
int C = 100;
const int CC = 1000;
int *p;
const int *A1 = &B1; //const修饰A指向的对象B,A可变,A指向的对象B不可变
int const *A2 = &B2; //同上
int * const A3 = &B3; //const修饰指针A,A不可变,A指向的对象B可变。
const int * const A4 = &B4; //指针A和A指向的对象B都不可变
int const * const A5 = &B5; //同上
/*
int * const A3;// = &B3; //const修饰指针A,A不可变,A指向的对象B可变。
const int * const A4;// = &B4; //指针A和A指向的对象B都不可变
int const * const A5;// = &B5; //同上
A3 = &B3; //const修饰指针A,A不可变,A指向的对象B可变。
A4 = &B4; //指针A和A指向的对象B都不可变
A5 = &B5; //同上
*/
/*
cout<<"样例1: +++++++++++++++++++修改指针+++++++++++++++++++"<<endl;
A1 = &C;
A2 = &C;
//A3 = &C; //error: assignment of read-only variable 'A3'
//A4 = &C; //error: assignment of read-only variable 'A4'
//A5 = &C; //error: assignment of read-only variable 'A5'
cout<<"A1:"<<*A1<<endl;
cout<<"A2:"<<*A2<<endl;
cout<<"A3:"<<*A3<<endl;
cout<<"A4:"<<*A4<<endl;
cout<<"A5:"<<*A5<<endl;
*/
/*
cout<<"样例3: +++++++++++++++++++修改指针指向静态变量(关注指针p与A1,A2)+++++++++++++++++++"<<endl;
//p = &CC; //error: invalid conversion from 'const int*' to 'int*'
A1 = &CC;
A2 = &CC;
//A3 = &CC; //error: assignment of read-only variable 'A3'
//A4 = &CC; //error: assignment of read-only variable 'A4'
//A5 = &CC; //error: assignment of read-only variable 'A5'
cout<<"A1:"<<*A1<<endl;
cout<<"A2:"<<*A2<<endl;
cout<<"A3:"<<*A3<<endl;
cout<<"A4:"<<*A4<<endl;
cout<<"A5:"<<*A5<<endl;
*/
/*
cout<<"样例2: +++++++++++++++++++修改对象的值+++++++++++++++++++"<<endl;
B1 = 101;
B2 = 102;
B3 = 103;
B4 = 104;
B5 = 105;
cout<<"A1:"<<*A1<<endl;
cout<<"A2:"<<*A2<<endl;
cout<<"A3:"<<*A3<<endl;
cout<<"A4:"<<*A4<<endl;
cout<<"A5:"<<*A5<<endl;
*/
cout<<"样例4: +++++++++++++++++++通过指针修改变量+++++++++++++++++++"<<endl;
//*A1 = 111;//error: assignment of read-only location '* A1'|
//*A2 = 112; //error: assignment of read-only location '* A2'|
*A3 = 113; //
//*A4 = 114; //error: assignment of read-only location '*(const int*)A4'|
//*A5 = 115; //error: assignment of read-only location '*(const int*)A5'|
cout<<"A1:"<<*A1<<endl;
cout<<"A2:"<<*A2<<endl;
cout<<"A3:"<<*A3<<endl;
cout<<"A4:"<<*A4<<endl;
cout<<"A5:"<<*A5<<endl;
return 0;
}
/*总结:
1. const与*的相对位置是十分关键的,而与数据类型(比如int)的相对位置无关。
2. const靠近(在*右侧)指针变量,则指针变量为只读指针,即指针的指向不可改变。
3. const远离(在*的左侧),则指针变量为指向只读变量的指针,即该指针可以只读变量。
4. 样例1,3的结果发现:A3,A4,A5是只读指针,即他们的指向是不可改变的,只能在定义时就要赋值,而且必须在定义时进行初始化,不然就会编译出错。
5. 样例3中对比指针p与指针A1,A2,我们发现,普通指针p是不能指向只读变量CC的,这就是A1,A2这一类指针的应用场景。
6. 样例2,4的结果发现,const*的指针指向的变量可以自己改变值,但不能通过指针进行修改变量的值。
6. 样例2的结果,我们发现,可以把带const的指针视作一种高级指针,可以用它们指向普通变量。
*/