/
27
. Create a
const
array of
double
and a
volatile
array of
// double. Index through each array and use const_cast to
// cast each element to non-const and non-volatile,
// respectively, and assign a value to each element.
#include < iostream >
#include < iomanip.h >
void main () {
const double ca[ 5 ] = { 0 , 1 , 2 , 3 , 4 };
volatile double va[ 5 ] = { 11 , 12 , 13 , 14 , 15 };
// 显示两个数组的值
for ( int i = 0 ;i < 5 ;i ++ ) {
cout << " ca[ " << i << " ] " << setw( 3 ) << ca[i] << ' ' ;
}
cout << endl;
for (i = 0 ;i < 5 ;i ++ ) {
cout << " va[ " << i << " ] " << setw( 3 ) << va[i] << ' ' ;
}
cout << endl;
double * a = const_cast < double *> (ca);
double * b = const_cast < double *> (va);
// 修改ca数组的值
for (i = 0 ;i < 5 ;i ++ ) {
a[i] = i * 2 ;
}
// 修改va数组的值,实际上va数组不用被const_cast也可以直接修改,但就不能被指针指了,要被指针指,必须const_cast。
for (i = 0 ;i < 5 ;i ++ ) {
b[i] = i * 3 ;
}
// 显示ca,va数组的值,被修改过了
for (i = 0 ;i < 5 ;i ++ ) {
cout << " ca[ " << i << " ] " << setw( 3 ) << ca[i] << ' ' ;
}
cout << endl;
for (i = 0 ;i < 5 ;i ++ ) {
cout << " va[ " << i << " ] " << setw( 3 ) << va[i] << ' ' ;
}
cout << endl;
}
// double. Index through each array and use const_cast to
// cast each element to non-const and non-volatile,
// respectively, and assign a value to each element.
#include < iostream >
#include < iomanip.h >
void main () {
const double ca[ 5 ] = { 0 , 1 , 2 , 3 , 4 };
volatile double va[ 5 ] = { 11 , 12 , 13 , 14 , 15 };
// 显示两个数组的值
for ( int i = 0 ;i < 5 ;i ++ ) {
cout << " ca[ " << i << " ] " << setw( 3 ) << ca[i] << ' ' ;
}
cout << endl;
for (i = 0 ;i < 5 ;i ++ ) {
cout << " va[ " << i << " ] " << setw( 3 ) << va[i] << ' ' ;
}
cout << endl;
double * a = const_cast < double *> (ca);
double * b = const_cast < double *> (va);
// 修改ca数组的值
for (i = 0 ;i < 5 ;i ++ ) {
a[i] = i * 2 ;
}
// 修改va数组的值,实际上va数组不用被const_cast也可以直接修改,但就不能被指针指了,要被指针指,必须const_cast。
for (i = 0 ;i < 5 ;i ++ ) {
b[i] = i * 3 ;
}
// 显示ca,va数组的值,被修改过了
for (i = 0 ;i < 5 ;i ++ ) {
cout << " ca[ " << i << " ] " << setw( 3 ) << ca[i] << ' ' ;
}
cout << endl;
for (i = 0 ;i < 5 ;i ++ ) {
cout << " va[ " << i << " ] " << setw( 3 ) << va[i] << ' ' ;
}
cout << endl;
}