Scope of private in C ++, const object calling non-const Functions

Source: Internet
Author: User

I recently learned C ++ and used the copy constructor to raise some questions.

 1   Class  Test {  2   Private  :  3       Int  A;  4   Public  :  5   Test ();  6 Test ( Const Test &T ){  7 A = T.;  8   };  9 ~ Test ();  10         Int Getdate (); //  Returns the value of A, so I will not write it.  11 }

In this way, the value of member variable A of t can be directly assigned to a of this class. This shows that the scope of private is relative to the class, rather than the class of an object. As long as it is in a class with the same name, private variables can be directly called.

Then I changed it.

 1  Class  Test {  2   Private  :  3       Int  A;  4   Public  :  5   Test ();  6 Test ( Const Test & T ){  7 A = T. getdata ();  8   };  9 ~ Test ();  10         Int Getdate (); //  Returns the value of A, so I will not write it.  11 }

The compiler reports an error. The reason is that when the const object calls its own function, it will automatically convert the function to the const this pointer, that is to say, it will change the function to the const type, and the getdata in the class is not the const type, therefore, an error is reported.

The modification method is int getdata () const;

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.