關(guān)于const *
和* const
的理解,可以參考[C C++ OC指針常量和常量指針區(qū)別]這篇文章被饿。
該篇文章中提到一個訣竅:** (指針) const(常量) 誰在前先讀誰丰捷,誰在前誰不允許改變菠净。*
我個人的記憶方法是:const修飾誰擦囊,誰就不可變塞茅。
int a = 10;
int b = 20;
int * const constValue = &a;
const int * constPValue = &b;
NSLog(@"constValue = %d, constPValue = %d", *constValue, *constPValue);
//constValue = &b; //報錯歼培,constValue是不可變的
*constValue = 15;
//*constPValue = 25; //報錯震蒋,*constPValue是不可變的
constPValue = &a;
NSLog(@"constValue = %d, constPValue = %d", *constValue, *constPValue);
打印結(jié)果為:
constValue = 10, constPValue = 20
constValue = 15, constPValue = 15
- 代碼
int * const constValue
中const
修飾constValue
,所以constValue
是不可變的躲庄,在初始化后對它賦值就會報錯查剖。
const在此處的影響: constValue不能再指向其他內(nèi)存,但是constValue當(dāng)前指向的內(nèi)存中的值可以改變
- 代碼
const int * constPValue
中const
修飾的是*constPValue
读跷,所以*constPValue
是不可變的梗搅。
const在此處的影響:constPValue當(dāng)前指向的內(nèi)存中的值不可以被改變(特指通過constPValue改變),但是可以指向其他內(nèi)存效览。
const int a;