const 和 引用 指针
来源:互联网 发布:性价比高的汽车知乎 编辑:程序博客网 时间:2024/05/19 17:47
const对象:
必须进行初始化,默认是定义该对象文件的局部变量。其他文件要想使用必须在定义的时候加上extern。
1 //file1.cpp 2 extern const int a = 1; 3 4 //main.cpp 5 #include <iostream> 6 7 using namespace std; 8 9 extern const int a ;10 11 int main()12 {13 cout << a << endl;14 return 0;15 }
如果是字面常量初始化,可以定义在头文件中,也不会造成多重定义,因为默认是局部变量。但是如果其他初始化就不能定义在头文件中。
1 //"file1.h" 2 #ifndef _FILE_H_ 3 #define _FILE_H_ 4 5 extern const int a = 1;//可以在头文件中定义字面常量初始化的const对象 6 7 #endif 8 9 //main.cpp10 #include <iostream>11 12 using namespace std;13 14 extern const int a ;15 16 int main()17 {18 cout<< a <<endl;19 return 0;20 }
引用: 是复合类型。引用是变量的别名,不能引用引用类型的引用,但可以引用其他类型的引用。
1 //不能引用引用类型的引用2 int a = 1 ;3 4 int &ra = a;//ok5 6 int && rra = ra;//error
可以声明const引用,extern const int &ra;
const 引用可以绑定到不同类型的对象或直接绑定到右值。而非const引用必须绑定到为同类型的对象。
1 double a = 1.0; 2 3 int &ra = a; 4 /************************ 5 * 不同类型的引用出现了中间值 6 * double a = 1.0; 7 * int tmp = (int)a;//tmp = 1; 8 * int &ra = tmp;10 * 如果改变引用ra的值只能够改变tmp的值,而不能改变a的值。11 *12 ************************/13 14 const double a = 1.0;15 16 const int &ra = a;17 /*************************18 * 同样出现了中间值tmp19 * const double a = 1.0;20 * const int tmp = (cosnt int)a;21 * const int &ra = tmp;22 * 但是const引用是 只读的,所以就不能改更ra的值23 * 也就不会引起tmp和a的值的变化24 *************************/
1 #include <iostream> 2 3 using namespace std; 4 5 int main () 6 { 7 const int &ra = 1; 8 cout << ra <<endl; 9 return 0;10 }
指针和引用差别:
1.指针更改所指向的对象,而引用从一而终。
int a = 1, b =3;int *pa = &a;int &ra = a;pa = &b;//okint &ra = b;//error
2.指针可以为空,引用不能为空。
int * p;//okint &ra;//error
3.有所有元素为指针的数组,但是没有所有元素为引用的数组。
int * a[10];//okint & ra[10];//error
4.指针的实质就是存储地址的变量,而引用则是一个变量的别名。
指针:
const对象必须用const指针指向,但是const指针未必指向const对象。
typedef string * pstring;
const pstring pst;
pst为const的string类型的指针,
- const引用和const指针
- const指针和const引用
- const 和 引用 指针
- const 指针和引用
- 引用、指针和const
- 指针和引用,const 指针和const 引用
- C++:指针、引用和CONST
- const的指针和引用
- 引用&指针和引用&const的关系
- 引用,const引用,指针
- const修饰指针和引用释疑
- const修饰指针和引用释疑
- 引用(reference)和const指针的区别
- const修饰指针和引用的用法
- 【杂记】引用和指针以及const
- const修饰指针和引用的用法
- const修饰指针和引用的用法
- const修饰指针和引用的用法
- 安装ADT的时候报错了(关于requires 'org.eclipse.gef 0.0.0' but it could not be found的解决方法)
- FLEX元标签_Inspectable
- 用extern定义全局变量
- windows下使用GUI 把本地代码提交到git远程仓库
- Android布局问题--ExpandableListView的ChildView布局不能居中的问题
- const 和 引用 指针
- IOS注意事项(2)
- jar命令及jar包详解
- 【Android UI】 Shape详解 (GradientDrawable)
- No row with the given identifier exists
- 网站图标Icon添加方法
- 黑马程序员_多线程2
- ubuntu中安装gstreamer开发环境(转)
- 字符串的操作 a