C + + const and const_cast

Source: Internet
Author: User

*************************************** 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.