理解复杂的声明2

来源:互联网 发布:newman 网络引论 编辑:程序博客网 时间:2024/05/16 05:41
const修饰符  
当你想阻止一个变量被改变,可能会用到const关键字。在你给一个变量加上const修饰符的同时,通常需要对它进行初始化,因为以后的任何 


时候你将没有机会再去改变它。例如:  


const int n=5;  
int const m=10;  


上述两个变量n和m其实是同一种类型的--都是const int(整形恒量)。因为C++标准规定,const关键字放在类型或变量名之前等价的。我个人 


更喜欢第一种声明方式,因为它更突出了const修饰符的作用。  


当const与指针一起使用时,容易让人感到迷惑。例如,我们来看一下下面的p和q的声明:  


const int *p;  
int const *q;  


他们当中哪一个代表const int类型的指针(const直接修饰int),哪一个代表int类型的const指针(const直接修饰指针)?实际上,p和q都 


被声明为const int类型的指针。而int类型的const指针应该这样声明:  


int * const r= &n; // n has been declared as an int  


这里,p和q都是指向const int类型的指针,也就是说,你在以后的程序里不能改变*p的值。而r是一个const指针,它在声明的时候被初始化指 


向变量n(即r=&n;)之后,r的值将不再允许被改变(但*r的值可以改变)。  


组合上述两种const修饰的情况,我们来声明一个指向const int类型的const指针,如下:  


const int * const p=&n // n has been declared as const int  
下面给出的一些关于const的声明,将帮助你彻底理清const的用法。不过请注意,下面的一些声明是不能被编译通过的,因为他们需要在声明 


的同时进行初始化。为了简洁起见,我忽略了初始化部分;因为加入初始化代码的话,下面每个声明都将增加两行代码。  


char ** p1;          //    pointer to    pointer to    char  
const char **p2;        //    pointer to    pointer to const char  
char * const * p3;       //    pointer to const pointer to    char  
const char * const * p4;    //    pointer to const pointer to const char  
char ** const p5;       // const pointer to    pointer to    char  
const char ** const p6;    // const pointer to    pointer to const char  
char * const * const p7;    // const pointer to const pointer to    char  
const char * const * const p8; // const pointer to const pointer to const char  


注: 
p1是指向char类型的指针的指针; 
p2是指向const char类型的指针的指针; 
p3是指向char类型的const指针; 
p4是指向const char类型的const指针; 
p5是指向char类型的指针的const指针; 
p6是指向const char类型的指针的const指针; 
p7是指向char类型const指针的const指针; 
p8是指向const char类型的const指针的const指针。  
0 0