[关键字]const用法集锦
来源:互联网 发布:软件需求变更管理 编辑:程序博客网 时间:2024/05/18 01:07
const
作用:防止定义的变量or对象再次被修改
注意:const修饰的变量必须在定义时初始化,(当作为类的数据成员时例外)
用法如下:
1:修饰整个函数(常函数):防止修改非static成员变量
//常函数作用:防止修改非静态(static)成员变量//即static成员变量可以改变,其他变量无法改变class Example{private:int a;static int b;public:void fun()const{a = 10;//错误!!!b = 10;}};
2:修饰指针:防止*ptr或者ptr被修改
const出现在*的左边,*ptr无法改变
出现在*的右边,ptr 无法改变
//修饰指针int a = 0;int b = 0;const int *ptr = &a;//修饰*ptr:不能通过*ptr改变a的值 *ptr = 10错误int const *ptr = &a;//修饰*ptr:不能通过*ptr改变a的值 *ptr = 10错误int *const ptr = &a;//修饰ptr :不能改变ptr的指向 ptr = &b错误const int* const ptr = &a;//*ptr以及ptr都无法改变
3:修饰函数返回值:防止函数返回值被改变
//修饰返回值const int Max(int &a, int &b){return a > b ? a : b;}int &c = Max(a,b)错误
const int &c = Max(a,b)正确
4:修饰函数参数:当以引用或者指针传递函数参数时,如果函数参数不想被改变,可以加const保护
char *Strcpy(const char *src, char *dest){assert(src != NULL);assert(dest != NULL);char *ret = dest;while(*dest++ = *src++);return ret;}
5:修饰变量:防止变量被修改
const int b = 0;b = 10;//错误
定义类时无法初始化数据成员,因为编译器不为类分配存储空间,定义对象时才会分配存储空间,const不是要在定义时初始化么,那么该怎么办呢??
const修饰的变量作为类的数据成员时,只能通过构造函数初始化,非静态数据成员无法在类外初始化
类的静态数据成员只能在类外初始化
class Example{private:int a = 10;//类不占用存储空间,在类中无法初始化数据成员const int b = 10;static const int c = 10;};//以上定义都是错误的
class Example{private:int a;const int b; //const修饰的变量作为类的数据成员时,只能通过构造函数初始化,非静态数据成员无法在类外初始化static int c;//类的静态数据成员只能在类外初始化public:Example(int x, int y);};static int c = 0;Example::Example(int x, int y) :a(x), b(y){}int main(){Example a(0, 0);system("pause");return 0;}
const定义的变量, 系统只为它分配一次内存, 而使用#define定义的常量宏, 定义几次分配几次, 这样const就很节约空间
#define PI 3.14 //使用#define宏const double Pi = 3.14; //使用const,这时候Pi并没有放入内存中double a = Pi; //这时候才为Pi分配内存,不过后面再有这样的定义也不会再分配内存double b = Pi; //不会再分配内存,double c = PI; //编译时分配内double d = PI; //编译时再分配内存
8:
const定义的变量只能作用于定义它的该文件, 不能被该程序的其他C/C++文件调用,
如file1.cpp中 const int val;
在file2.cpp中, extern int val; //错误,无法调用,
要想const定义的变量能被其他文件调用, 定义时必须使用extern修饰
如file1.cpp中 extern const int val = 10;
在file2.cpp中 extern const int val; //正确,可以调用,
非const变量默认为extern, 要使const修饰的变量能被其他文件访问必须显示指定为extern
- [关键字]const用法集锦
- const关键字的用法
- const关键字用法
- Const关键字用法
- const关键字的用法
- 关键字const用法详解
- const关键字的用法
- Const关键字的用法
- const关键字用法
- const 关键字基础用法
- const关键字的用法
- const关键字的用法
- const关键字的用法
- const关键字的用法
- C++关键字const用法详解
- C语言关键字const用法
- C++关键字const基本用法
- const关键字的深度用法
- Map集合的使用
- http请求的基本过程
- JAVA操作HDFS API(hadoop) HDFS API详解
- 太用力的人跑不远
- C++函数的哑元及其作用
- [关键字]const用法集锦
- 深拷贝的一种实现方法
- 手机游戏刷表流程记录—服务端菜鸟的成长之路
- Ubuntu15.04编译php
- redis错误集
- Next Permutation
- Android应用setContentView与LayoutInflater加载解析机制源码分析
- IntelliJ 出现 cannot resolve symbol.
- Android Studio 报No resource found that matches the given name '@style/Theme.AppCompat.Light'.