#include
using namespace std;
int main()
{
int a1 = 13;
int a2 = 19;
int const p1 = 0;
const int p2 = 0; // p1 和 p2 完全一样
/* error: invalid conversion from 'const int *' to 'int *'
'&p1' is 'const int *'
'p3' is 'int *'
此处声明的p3是int*的const,自身不可变,而指向的数据可变,
然而,现在指向的p1是const,不可变,所以编译器报错
*/ // int * const p3 = &p1;
int * const p3 = &a1; // ok
// p3 = &a2; //p3 不可变, error: assignment of read-only variable 'p3'
(*p3)++; // ok! equal a1++;
int const * p4 = &p1;
p4 = &a2; // ok!
// (*p4)++; //p4 指向的数据不可变, error: increment of read-only location '* p4'
const int * p5 = &p2; // p4 和 p5 完全一样
p5 = &a2;
// (*p5)++;
const int * const p6 = &a1; // ok!
// p6 = &a2; // error: assignment of read-only variable 'p6'
// (*p6)++; // error: increment of read-only location '*(const int*)p6'
const int * const p7 = &p1; // ok!
// p7 = &a2; // 同p6
// (*p7)++; // 同p6
cout << "p3 = " << p3 << ", *p3 = " << *p3 << endl;
cout << "p4 = " << p4 << ", *p4 = " << *p4 << endl;
cout << "p5 = " << p5 << ", *p5 = " << *p5 << endl;
cout << "p6 = " << p6 << ", *p6 = " << *p6 << endl;
cout << "p7 = " << p7 << ", *p7 = " << *p7 << endl;
return 0;
}
运行结果: