我们都知道C++中数组名实际上是数组头指针,在函数中我们不希望改变数组中元素的值,但是由于疏忽却有可能无意中改变
下面这样的做法可以一定程度上避免这种情况
#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr(const int * begin,const int * end);
int main(){
int cookies[ArSize] = {1,2,4,8,16,32,64,128};
cout<<"sum:"<<sum_arr(cookies,cookies+ArSize);
cout<<"first 3:"<<sum_arr(cookies,cookies+3);
cout<<"last 4:"<<sum_arr(cookies+4,cookies+8);
return 0;
}
int sum_arr(const int * begin,const int * end){
const int * pt;
int total = 0;
for(pt = begin;pt!=end;pt++){
total+=*pt;
}
return total;
}
在函数原型与函数声明的参数列表的类型前加上const关键字,就可以避免修改例如 *begin指向的值,但是我们依然能够修改begin的值
比如下面就修改了begin的值(const 类型 * 类似声明是避免修改指针指向的值,而不是指针的值)
int sum_arr(const int * begin,const int * end){
const int * pt;
int total = 0;
begin++;
for(pt = begin;pt!=end;pt++){
total+=*pt;
}
return total;
}
下面这样就能够避免修改指针的值
int sum_arr(int * const begin,const int * end);//原型也做对应修改
int sum_arr(int * const begin,const int * end){
const int * pt;
int total = 0;
//begin++; 此时如果执行此操作将会报错
for(pt = begin;pt!=end;pt++){
total+=*pt;
}
return total;
}
给出总结
1.const 类型 * 名字 意为:一个指向常量的指针
2.类型 * const 名字 意味:指向某种类型的常量指针