码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 的 const和const_cast

时间:2015-04-26 19:48:43      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:c++   const   const_cast   

***************************************转载请注明出处:http://blog.csdn.net/lttree********************************************



今天,逛了逛 问答社区,

在C++ 里,看到有人问关于 const_cast 的东西,

正好在 <<Effective C++>> 中,也讲到过这方面的东西。

翻了翻书,上网搜了搜,

发现还挺好玩....


题主问的是如何将一个设定为 const 的 double 类型数组  在运行期间  对它再解除const,然后改动数组内容。


> 首先,明确一下,

对于 const_cast  

这个东西,只是对于指针 和 引用 解const,对于变量,就会出现问题。

比如,看下面这段代码:

const int a=789 ;
int &b = const_cast<int&>(a);
int *c = const_cast<int*>(&a);
	
cout<<"a="<<a<<endl;
cout<<"&b="<<b<<endl;
cout<<"*c="<<*c<<endl;
cout << "&a="<<&a<<endl;
cout << "&b="<<&b<<endl;
cout << "c="<<c<<endl;
cout<<endl;

b = 987;
*c = 999;
cout << "a="<<a<<endl;
cout << "b="<<b<<endl;
cout << "*c="<<*c<<endl;
cout << "&a="<<&a<<endl;
cout << "&b="<<&b<<endl;
cout << "c="<<c<<endl;

运行一下:

技术分享


很好玩吧~。~




> 然后,对于这个问题,

因为是数组,数组属于指针的范畴了,

我就试着写了写,

发现,

通过一个中间变量,还是可以改动原来的const的内容的:

const double arr[3] = {1.2,3.3,4.5};
int i;
for(i=0;i<3;++i)
	cout<<arr[i]<<" ";
cout<<endl;

double& temp = const_cast<double&>(arr[0]);

for(i=0;i<3;++i)
	cout<<arr[i]<<" ";
cout<<endl;

cout<<temp<<endl;
cout<<arr[0]<<endl;
cout<<&temp<<endl;
cout<<&arr[0]<<endl;

结果还是可以的

技术分享


OK,就是这样,

挺有意思的东东~。~




***************************************转载请注明出处:http://blog.csdn.net/lttree********************************************

C++ 的 const和const_cast

标签:c++   const   const_cast   

原文地址:http://blog.csdn.net/lttree/article/details/45291029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!