The object of the class cannot directly access the private member variable of the class declaration, otherwise it destroys the purpose of information hiding.
In C + +, to prevent some data members or member functions from being accessed directly from the outside, you can declare them private so that the compiler blocks any direct access from external non-friends.
The common access methods for private member variables are as follows:
(1) Assigning a value to a private member through a public function
#include <iostream> 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=" <<x<< ' \ t ' << "y=" <<y<<endl; } } ; int main () { Test p1; P1.setx (1); P1.sety (9); P1.print (); return 0; }
(2) accessing private data members with pointers
#include <iostream> 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); Will A=x, b=y cout<<a<< ' \ t ' <<b<<endl; return 0; }
(3) Accessing private data members with functions
#include <iostream> 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; Returns the Y value } }; int main () { Test p1; P1.setx (1); P1.sety (9); int a, B; A=p1.getx (); B=p1.gety (); cout<<a<< ' \ t ' <<b<<endl; return 0; }
(4) Accessing private data members with references
#include <iostream> 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); Will A=x, b=y cout<<a<< ' \ t ' <<b<<endl; return 0; }
Common methods for accessing private member variables in C + +