For methods to access private member variables in C ++ class objects, user Meta is not considered.

Source: Internet
Author: User

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 .}
 

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.