目录
- const 和 数据类型可以交换
- 跟指针一样,const修饰的是右边的变量
- 常引用可以指向常量,当做常量使用
- 常引用 指向 表达式
- 常引用作为函数形参可以接收 const类型 和 非 const类型,常引用 和 非const引用可以构成函数重载
- 指针形参的const和非const也能构成重载,跟const 引用一样
- 普通的形参变量 const和 非const 无法构成重载
- 引用数组的2种格式:
const 引用,又叫常引用,引用的本质是指针,所以很多东西都是相通的.
const 和 数据类型可以交换
下面代码 int const 和 const int作用一样
int a = 1;
int const &ref = a;
const int &ref = a;
跟指针一样,const修饰的是右边的变量
int const 和 const int可以交换,所以修饰的是int,表示int是不能改变的
int a = 1;
int const &ref = a;
// ref = 10;//错误,常引用不能修改值
const int &ref2 = a; //const int 等价于 int const,因为const 和数据类型可以交换
// ref2 = 20;
常引用可以指向常量,当做常量使用
作用可以看做是 swift中的let width = 100
如下
int const &ref3 = 30; //当做常量使用,因为30是不能改变的,所以 常引用 ref3可以指向30
cout << ref3 <<endl;
常引用 指向 表达式
常引用右边可以是个表达式,例如一个函数,函数返回值需要是常量const
int sum(){
return 10;
}
void main(int argc, const char * argv[]) {
const int &ref4 = sum();//因为sum的返回值是常量,所以用常引用可以使用
}
常引用作为函数形参可以接收 const类型 和 非 const类型,常引用 和 非const引用可以构成函数重载
int sum2(const int &a,const int &b){
cout<< " sum2(const int &a,const int &b)"<< endl;
return a + b;
}
int sum2( int &a,int &b){
cout<< "sum2( nt &a,int &b)"<< endl;
return a + b;
}
void main(int argc, const char * argv[]) {
int result = sum2(10,20);
int a1 = 1;
int a2 = 2;
int result2 = sum2(a1, a2);//a1,a2都是变量,但是可以可以传给 const 形参函数
}
运行结果:
sum2(const int &a,const int &b)
sum2( nt &a,int &b)
指针形参的const和非const也能构成重载,跟const 引用一样
void sum3(const int *p1, const int *p2){
cout << "sum3(const int *p1, const int *p2)" <<endl;
}
void sum3( int *p1, int *p2){
cout << " sum3( int *p1, int *p2)" <<endl;
}
void main(int argc, const char * argv[]) {
sum3(&a1, &a2);
const int *p1 = &a1;
const int *p2 = &a2;
sum3(p1, p2);
}
普通的形参变量 const和 非const 无法构成重载
void sum4( int a, int b){
cout << " sum4( int a, int b)" <<endl;
}
//但是普通的形参变量 const和 非const 无法构成重载
void sum4( const int a,const int b){
cout << " sum4( int a, int b)" <<endl;
}
//这里会报错:Redefinition of 'sum4' 表示重定义了sum4,因为2个sum4不能重载
引用数组的2种格式:
- int (&ref1)[3] = arr;
- int * const &ref2 = arr;
int arr[] = {1,2,3};
//数组的引用格式1
int (&ref1)[3] = arr;
ref1[0] = 10;
//数组的引用格式2
int * const &ref2 = arr;
ref2[1] = 20;
for (int i = 0 ;i < 3 ; i++){
cout<< arr[i] << endl;
}