CHAPTER 03:EX 27

/ 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值