C++const關鍵字和指標的結合使用
阿新 • • 發佈:2020-08-08
#include<iostream> using namespace std; /** * C++const關鍵字和指標的結合使用 * 1,指標常量:可以修改指標變數指向地址的值,不能修改指標變數的指向(即可以給*p賦值, 不能給p賦值) * 語法: dataType *const pointerVariableName = &variableName; * 2,常量的指標:不可以修改指標變數指向地址的值,能修改指標變數的指向(即可以給p賦值, 不能給*p賦值) * 語法: const dataType *pointerVariableName = &variableName; * 3,指向常量的指標常量:不可以修改指標變數指向地址的值,也不能修改指標變數的指向(即不可以給p賦值, 不能給*p賦值) * 語法: const dataType *const pointerVariableName = &variableName;*/ int main() { int a = 10; int b = 20; //pointer constant int *const constP = &a; cout << "Before assignment again for value of variable which is pointed at pointer constant constP is " << *constP << endl; *constP = 100; cout << "After assignment again for value of variable which is pointed at pointer constant constP is" << *constP << endl; //constP = &b; //error: assignment of read-only variable 'constP' //constant's pointer const int *poc = &b; cout << "Before assignment again for constant's pointer poc, the value of constant which is point at constant's pointer is" << *poc << endl; poc = &a; cout << "After assignment again for constant's pointer poc, the value of constant which is point at constant's pointer is " << *poc << endl; //*poc = 100; //error: assignment of read-only location '* poc' //pointer constant's pointer const int *const constPoc = &b; //constPoc = &a; //error: assignment of read-only variable 'constPoc' //*constPoc = 100; //error: assignment of read-only location '*(const int*)constPoc' system("pause"); return 0; }
如何理解和記憶/區分指標常量和常量的指標?
看const關鍵字修飾的是什麼
形如:int *const p = &a;明顯const修飾的是變數p,變數p是什麼變數呢?
指標變數,即指標變數的值不能修改,而指標變數的值是地址,不能改變地址即不能改變指標變數的指向,即該指標變數是常量,故稱為指標常量
形如:const int *p = &a;明顯const修飾的變數*p,變數*p是什麼變數呢?
指向整型變數的指標p指向的變數,即一個整型變數,整型變數*p不能被修改即不能改變整型變數*p的值,即整型變數*p是個常量,故指標p被稱為指向常量的指標