*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************
Today, we visited the quiz community,
In C + +, I saw someone asking about const_cast,
Just in the <<effective c++>>, also talked about this aspect of things.
Turned over the book, the Internet search,
Found it kinda fun ....
The main question is how to set a const double type array to re-release the const during run time, then change the contents of the array.
> First, make it clear,
For const_cast
This thing, just for pointers and references to the solution const, for variables, there will be problems.
For example, look at the following code:
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;
Run it:
It's fun. ~
> Then, for this question,
Because it is an array, the array belongs to the category of pointers,
I just tried to write,
Found
Through an intermediate variable, you can still change the contents of the original 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;
The result is still possible.
OK, that's it,
Very interesting stuff ~. ~
*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************
C + + const and const_cast