Someone in the group asked this question at night:
class a { public: void GetValue() {cout<<k<<endl;} private: int k; };
It is required that you do not need to use a friend element. If you do not add any code in this class, change the value of member variable k to 100. The result is naturally verified by the Public member function getvalue.
The implementation is as follows:
class a { public: void GetValue() {cout<<k<<endl;} private: int k; }; int main(){a x;a *p=&x;*((int *)p)=100;cout<<&x<<endl;x.GetValue();return 0;}
The forced conversion character in C ++ is not used, and the forced conversion character in C is more inclined.
Implementation principle: the object address is the address of the first member variable.
The C ++ compiler separates data from program segments, and all class variables are stored in the 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.
For example:
class A{public:int i;void setJ(int _j){j = _j;};int getJ() const {return j;};private:int j;};
Int main () {A;. setj (2); printf ("the value of J before modification % d. N ",. getj (); // print the value of J before modification.Int * P = (int *) (INT (& A) + sizeof (a. I); * P = 10;Printf ("the Modified J value is % d. N", A. getj (); // print the Modified J value .}