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)是不能变的,详细见如下代码。
- #include<stdio.h>
- int main()
- {
- const int * a;
- int b;
- a=&b;
- b=5;
- (*a)=5;
- 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只能指向一个地址,但是地址里的内容是可以改的。
看如下代码
- #include<stdio.h>
- int main()
- {
- int * const a;
- }
- test.cpp: In function ‘int main()’:
- test.cpp:4: 错误:未初始化的常量 ‘a’
必须初始化。
然后再看
- #include<stdio.h>
- int main()
- {
- int b;
- int c;
- int * const a=&b;
- (*a)=5;
- a=&c;
- }
- test.cpp: In function ‘int main()’:
- test.cpp:8: 错误:assignment of read-only variable ‘a’
const int * const a;
这个就是定死了,a也不能修改,(*a)也不能修改,而且a必须初始化。
- #include<stdio.h>
- int main()
- {
- int b;
- int c;
- int const* const a=&b;
- (*a)=5;
- a=&c;
- }
- test.cpp: In function ‘int main()’:
- test.cpp:7: 错误:assignment of read-only location
- test.cpp:8: 错误:assignment of read-only variable ‘a’
还有其中区别方法:
沿着*号划一条线,
如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;
如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。
(未完待续)