In principle, private variables in the C ++ class are not allowed to be accessed anywhere outside of the class. Generally, a fully functional class provides the get and set methods to operate class attribute values, however, if no get or set method is provided, for example, it is provided by a third party. O (or dynamic library) for development, and in actual applications, we actually need to change a private parameter of an object. Is there any way? We know that a process has Program Segment and data segment. If we know the data space of the object, it is easy to get the member variable value of the object. In fact, the first address of the object data segment is actually the object address, for example:
Class
{
Public:
Int I;
Bool setj (INT _ j) {J = _ j ;};
Int getj () const {return J ;};
PRIVATE:
Int J;
};
Int main ()
{
A;
Printf ("A's address is % u. n", & A); // print the address of object
Printf ("A. I's address is % u. n", (& (a. I); // print the address of member variable I of object
}
Run the above program and we can see that the two values are the same, that is, the object address is the address of the first member variable.
We know that the C ++ compiler separates data from program segments, and all class variables are stored in data segments in order of declaration. Therefore, if you know the address of the first variable, then the following addresses are accumulated one by one. With the variable address, you can modify its value. The preceding example shows how to change the value of class member B:
Int main ()
{
A;
A. setj (2 );
Printf ("before modified: The member J of A is % d. N", A. getj (); // print the value of J.
Int * P = (int *) (INT (& A) + sizeof (a. I ));
* P = 10;
Printf ("after modified: The member J of A is % d. N", A. getj (); // print the value of J.
}
We can see that the value of the J member variable is changed from 2 to 10.
Conclusion: Please be careful when operating on the address space directly...