const和引用
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.cpp 10 #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;//ok 5 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 * 同样出现了中间值tmp 19 * 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 }
浙公网安备 33010602011771号