1. 指向const對象的非const指針(常用于函數的形參)
指針指向一個const對象,不允許通過指針修改其指向的const對象的值。
但是指針本身的值是可以修改的(可以指向另一個對象)。
void testConstPointer1()
{
const string s1 = "alexzhou";
const string *ps1 = &s1;
//*ps1 = "zjh";編譯錯誤
cout << *ps1 << endl;
const string s2 = "zjh";
ps1 = &s2;
cout << *ps1 << endl;
}
把const對象的位址指派給一個非const對象的指針是錯誤的,如:
const string s1 = “alexzhou”;
string *ps1 = &s1;//error
同理不能使用void*指針儲存const對象的位址,需要使用const void*。
但允許把非const對象指派給const對象的指針。
const string *ps1;
string s3 = “zjh”;
ps1 = &s3;//ok
由于沒有辦法分辨ps1所指的對象是否為const,是以系統會把它所指的對象視為const的。是以不能通過ps1修改它所指的非const對象的值。
2. 指向非const對象的const指針
指針本身的值不能修改(不能指向另外一個對象),但是指針所指的對象的值是可以修改的。
void testConstPointer2()
{
string s1 = "alexzhou";
string s2 = "zjh";
string s3 = "alexzhou";
string *const ps1 = &s1;
*ps1 = "zjh";//ok
ps1 = &s2;//error
ps1 = &s3;//error
}
3. 指向const對象的const指針
既不能修改指針的指向,也不能修改指針所指對象的值。
voidtestConstPointer()
{
conststring s1 = "alexzhou";
conststring s2 = "alexzhou";
conststring *constps1 = &s1;
*ps1 = "zjh";//error
ps1 = &s2;//error
}
轉載請注明來自: Alex Zhou ,本文連結: http://codingnow.cn/c-c/486.html