C + +, a variable in a const object cannot be modified

Source: Internet
Author: User

A variable in a const object cannot be modified, even if a function in a const object cannot modify the value of a variable in that object

#include <iostream>using namespacestd;//-----------------------------------------------classTest { Public:    intx;    Test (); voidChangeinta);}; Test::test () { This->x = at;}voidTest::change (inta) {     This->x=A;}//-----------------------------------------------voidF1 () {Test T1; t1.x=111; cout<<"t1.x="<<t1.x<<Endl; T1.change (1111); cout<<"t1.x="<<t1.x<<Endl; ConstTest T2; cout<<"t2.x="<<t2.x<<Endl; //a variable in a const object cannot be modified, even if a function in a const object cannot modify the value of a variable in that object. //g++: Error:assignment of Data-member ' test::y ' in read-only structure//t2.x = ten;//vs2010 can be compiled through, but execution does not change the value of t2.x//cout<< "t2.x=" <<t2.x<<endl; //T2.change (2222);//error C2662: "Test::change": Cannot convert "This" pointer from "Const test" to "Test & "    }intMain () {F1 ();  while(1); return 0;}

C + +, a variable in a const object cannot be modified

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.