文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>const用法详解

const用法详解

时间:2010-10-14  来源:nxlhero

(以下代码用gcc或g++编译)

1.修饰普通变量

 const int a;

 int const a;

 这两种是一样的,没有区别,另外 int a const 是错误的。

 其实上述两种方式也是错的,必须初始化才行!

 如果不初始化,C++编译器会提示错误,没有initialize,而C编译器正常,但是如果在下面在赋值的话就错了,不能对常量赋值。

 

2.修饰指针变量

有很多种写法,逐个分析。

  const int * a; 

 这个const修饰的重点是int,也就是说,a并不是常量,a是可以变的,(*a)是不能变的,详细见如下代码。

  1. #include<stdio.h> 
  2. int main() 
  3.   const int * a; 
  4.   int b; 
  5.   a=&b; 
  6.   b=5; 
  7.   (*a)=5; 
  8.   return 0; 

test.cpp:8: 错误:assignment of read-only location
我们可以对b进行赋值,但是不能用(*a)对其赋值。明白了吧?

 int const * a;

 这个与 const int *a是一样的,a可以赋值,但是(*a)不能赋值。 

 

 int * const a;

 这个修饰的是a,a是什么类型的?a是指针类型,所以说a必须初始化,a只能指向一个地址,但是地址里的内容是可以改的。

 看如下代码

  1. #include<stdio.h> 
  2. int main() 
  3.  int * const a; 
  4. test.cpp: In function ‘int main()’: 
  5. test.cpp:4: 错误:未初始化的常量 ‘a’ 

必须初始化。

然后再看

  1. #include<stdio.h> 
  2. int main() 
  3.  int b; 
  4.  int c; 
  5.  int * const a=&b; 
  6.  (*a)=5; 
  7.  a=&c;  
  8. test.cpp: In function ‘int main()’: 
  9. test.cpp:8: 错误:assignment of read-only variable ‘a’ 

 const int * const a;

 这个就是定死了,a也不能修改,(*a)也不能修改,而且a必须初始化。

  1. #include<stdio.h> 
  2. int main() 
  3.  int b; 
  4.  int c; 
  5.  int constconst  a=&b; 
  6.  (*a)=5; 
  7.  a=&c; 
  8. test.cpp: In function ‘int main()’: 
  9. test.cpp:7: 错误:assignment of read-only location 
  10. test.cpp:8: 错误:assignment of read-only variable ‘a’ 

还有其中区别方法:

沿着*号划一条线,

如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;

如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。

(未完待续)

排行榜 更多 +
超级冒险王安卓版

超级冒险王安卓版

休闲益智 下载
玩具小镇手机版

玩具小镇手机版

休闲益智 下载
这一关特上头手机版

这一关特上头手机版

休闲益智 下载