先给出结论:
typedef int* PINT; // PINT <---> int*
typedef PINT const CPINT1; // CPINT1 <---> int* const
typedef const PINT CPINT2; // CPINT2 <---> int* const
typedef const int* CPINT3; // CPINT3 <---> const int*
typedef int* const CPINT4; // CPINT4 <---> int* const
为搞清楚 const 指针, 特地做了以下的测试:
// 变量准备
int nNum1 = 111;
int nNum2 = 222;
int* pNum1 = &nNum1;
int* pNum2 = &nNum2;
// effective c++中这么说:
// *号在const左边为const data; (只读指针)
// *号在const右边为const pointer;
// 之所以要这么记是因为 const int* p等同于int const *p
// 我的记法是 const 和变量名在一起的则是 const 指针,反之则是const data.
// 测试1
const int* ptr1 ( pNum1); // 初始化
//*ptr1 = nNum2; // error 只读指针。
ptr1 = pNum2; //ok
// 测试2
int* const ptr2 ( pNum1); // 初始化
*ptr2 = nNum2; // ok
//ptr2 = pNum2; // error, const指针
这个时候 做了次typedef, 出现了神奇的事情
typedef int* PINT;
// 测试3
const PINT ptr3 ( pNum1); // 初始化
*ptr3 = nNum2; //ok
//ptr3 = pNum2; // error,const指针
// 测试4
PINT const ptr4 ( &nNum1); // 初始化
*ptr4 = nNum2; // ok
//ptr4 = pNum2; // error,const指针
非常不解, 继续 typedef 加上const
typedef PINT const CPINT1;
typedef const PINT CPINT2;
// 测试5
CPINT2 ptr5 ( pNum1); // 初始化
*ptr5 = nNum2; //ok
//ptr5 = pNum2; // error,const指针
// 测试6
CPINT1 ptr6 ( pNum1); // 初始化
*ptr6 = nNum2; // ok
//ptr6 = pNum2; // error,const指针
还是一样, 最后 再试。
typedef const int* CPINT3;
typedef int* const CPINT4;
// 测试7
CPINT3 ptr7 ( pNum1); // 初始化
//*ptr7 = nNum2; // error
ptr7 = pNum2; // OK
// 测试8 :
CPINT4 ptr8 ( pNum1); // 初始化
*ptr8 = nNum2; // ok
//ptr8 = pNum2; // error,const指针
这次觉得结果就跟测试1, 测试2 一样了。