寫過一篇關於c++中const的總結,這裏詳細總結一下const和指針之間的關係
首先我們看一段代碼,就是字符數組的初始化問題
#include <iostream>
using namespace std;
int main()
{
const char *s = "const object";
//in C, we can use char *s
char s1[] = "const object";
const char s2[] = "const object";
//s[0] = 'C';//錯誤,修改字符常量
s1[0] = 'C';
//s2[0] = 'C';//錯誤,雖然是字符數組,但是有cosnt修飾
/*char s2[]; s3 = "const object";錯誤,字符數組不能這樣初始化*/
const char *s4;
s4 = "const object";//上面那種情況不可以,但是這種情況可以哦
return 0;
}
以上雖然問題不大,編譯器都會報錯,但是筆試的時候遇到了呢?還是注意爲妙
另外注意一點:在c++中,const char *s = "const object"和char *s = "const object"是一樣的,後者會產生warning ,但是在C程序中,後者沒問題
下面我們看const和指針之間糾纏不清的關係:
第一種情況:指向常量的非常量指針
#include <iostream>
using namespace std;
int main()
{
const char* coptr;//一個指向const對象的指針
coptr = "cosnt object";
cout<<coptr<<endl;
coptr[0] = 'C';//error:can't change the content of the const object
coptr = "Const object";//right
cout<<coptr<<endl;
char cptr1[] = "non-const object";//warning:should be const char *coptr1
//gcc will not warning
cptr1 = coptr;//把常量對象地址賦給非常量對象地址是錯誤的,想一下,如果我們修
改非常量對象是不是把常量對象修改了,這樣當然不可以了
coptr = cptr1;//把非常量對象地址賦給常量對象卻可以
return 0;
}
總結一下:指向常量對象的指針可以修改改指針的值,但是不能修改該指針指所向的值的值
第二種情況:指向非常量的常量指針
#include <iostream>
using namespace std;
int main()
{
char s[] = "const pointer";
char *const cptr = s;//指向非常量對象的const指針
cptr[0] = 'C';//right
char t[] = "another string";
//cptr = t;//error cptr is const
return 0;
}
總結一下:指向非常量的常量指針可以修改指針指向的值的值,但是不能修改指針的值,即初始化之後,指針只能指向這個值
第三種情況:指向常量的常量指針,當然是融合了上面兩種情況的特性
#include <iostream>
using namespace std;
int main()
{
const char *const cocptr = "const pointer to const object";
cocptr[0] = 'C';//error
char t[] = "another string";
cocptr = t;//error
return 0;
}
另外要注意:
指針常量的申明:const 放在* 和指針名之間 Type* const pointer ;
常量指針的申明:const放在類型說明符之前 const Type* pointer ;
我們可以這樣記憶: type* 爲指針 ,const爲常量 , type* const是指針常量,const type*是常量指針 詳見《c++ primer》p180
最後加上我的理解,爲什麼c/c++中要用這個const,因爲這和數據的屬性有關,有些數據可變,有些不可變,在程序的運行中這都是未知的,如果我們想要以可預見的方式控制程序的流程和數據的變動,就需要這種常量關鍵字的機制