const关键字的使用

来源:互联网 发布:中金智德 知乎 编辑:程序博客网 时间:2024/05/16 10:16

一:定义常量

(a)const修饰常量,含义是const修饰的类型为TYPE的变量value是不可变的:

TYPE const valuename = value;

const TYPE valuename = value; 

 (b)将const改为外部链接,作用扩大到全局,编译的时候会分配内存,并且可以不进行初始化,仅仅作为声明:

extend const int valuename = value;

二:指针使用const

(a)指针本身是常量不变,char* const pContent;

(b)指针所指向的内容是常量不可改变,const char* pContent;

(c)俩个都不可以改变,const char* const pContent;

三:函数中使用const

(a)const修饰函数参数

1:传递过来的参数在函数内不可以改变(无意义,因为Var本身就是形参)

void funtion(const int Var);

2:参数指针所指的内容是常量不改变

void function(const char* Var);

3:参数本身为常量不改变

void funtion(char* const Var);

4:参数为引用,为增加效率同时防止修改;

void funtion(const class& Var);

void funtion(const Type& Var);

(b)const修饰函数返回值

1:const int fun1();

2:const int* fun2();指针内容不可改变

3:int* const fun3();指针本身不改变

原创粉丝点击