c++ const 修饰数组

 

//直接声明为 int a[], 这样会允许函数内部对a[] 进行修改

void showTheWorld( int a[], int sizeOfa) {
for ( int i = 0; i < sizeOfa; i++)
cout << a[i] << " ";
cout << endl;
}

如果 声明为const int a[], C++就不允许函数内部在对a[] ,进行修改了

void showTheWorld( const int a[], int sizeOfa)
{
cout << "The array contains the following values:\n";
for ( int i = 0; i < sizeOfa; a[i]++) // a[i]++ 会改变a[] l里面的每个项加1;因为声明了const int  a[] ,这样编译器就会报错
cout << a[i] << " ";
cout << endl;
}

double computeAverage( int a[], int numberUsed); //声明一个参数 int a[] 不为const,

void showDifference( const int a[], int numberUsed)
{
double average = computeAverage(a, numberUsed); //调用computeAverage,编译器会认为computeAverage会改变a[] 数组,这与showDifference参数矛盾,报错
for ( int index = 0; index < numberUsed; index++)
cout << a[index] << " differs from average by "
<< (a[index] – average) << endl;
}//computeAverage 应该定义成

double computeAverage(  const  int a[], int numberUsed);

 

 

posted on 2012-10-30 11:39  GIS-MAN  阅读(4796)  评论(0编辑  收藏  举报

导航