C + + Private member variables are accessed directly by the object

Source: Internet
Author: User

C + + access control :

The keyword private, which describes access control for a class member. Private member functions and variables can be accessed directly using the class's object methods. The object of a class is that an instance can access private and private member functions only through public member functions. Therefore, the public member function becomes the bridge of the object's private variable access.

In C + +, a private member variable can be accessed directly through an object of the class type when the parameter to the member function of the class is such a type. Or use a temporary object in the member function to directly access the private variable.

Class Test{private:     int A;     int b;p ublic:     test (int x,int y)     {       a = x;       b = y;     };     Test () {a = 0;b = 0;};     Test Add (const test& one) const     {          test tmp;          Tmp.a = a + one.a;   The temporary object TMP uses the private variable directly. The Parameter object one can also directly use the temporary object          tmp.b = b + one.a;          return tmp;     };     void Show ()     {cout<<a<< "" <<b<<endl;};}

Test, two.a = 3; This time will not compile through. Because only within the member functions of the class, objects can use private variables directly.




C + + Private member variables are accessed directly by the object

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.