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 <