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);