Common Methods for c ++ to access private member variables

Source: Internet
Author: User
Tags gety

Common Methods for c ++ to access private member variables

Class objects cannot directly declare private member variables declared by the class; otherwise, Information Hiding is broken.
In C ++, to prevent some data members or member functions from being directly accessed from the outside, they can be declared as private, so that the compiler will block any direct access from external non-friends.
Common access to private member variables is as follows:

(1) assign values to private members using public functions

 

# Include
 
  
Using namespace std; class Test {private: int x, y; public: void setX (int a) {x = a;} void setY (int B) {y = B ;} void print (void) {cout <"x =" <(2) access private data members using pointers
  

 

 

# Include
   
    
Using namespace std; class Test {private: int x, y; public: void setX (int a) {x = a;} void setY (int B) {y = B ;} void getXY (int * px, int * py) {* px = x; // extract x, y value * py = y ;}}; int main () {Test p1; p1.setX (1); p1.setY (9); int a, B; p1.getXY (& a, & B); // convert a = x, B = y cout <(3) use functions to access private data members
    
# Include
     
      
Using namespace std; class Test {private: int x, y; public: void setX (int a) {x = a;} void setY (int B) {y = B ;} int getX (void) {return x; // return x value} int getY (void) {return y; // return y value }}; int main () {Test p1; p1.setX (1); p1.setY (9); int a, B; a = p1.getX (); B = p1.getY (); cout <
      

(4) access private data members using references

 

# Include
       
        
Using namespace std; class Test {private: int x, y; public: void setX (int a) {x = a;} void setY (int B) {y = B ;} void getXY (int & px, int & py) // reference {px = x; // extract x, y value py = y ;}}; int main () {Test p1, p2; p1.setX (1); p1.setY (9); int a, B; p1.getXY (a, B); // set a = x, B = y cout <
       

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.