zoukankan      html  css  js  c++  java
  • private成员变量真的私有吗?(用指针刨他祖坟)

    今天写程序时突然想到的,为什么不用指针去获取类的成员变量呢。于是做了这个实验。首先定义了一个类:

     1 class Test {
     2 private:
     3     int i;
     4     char c;
     5     int* p;
     6 public:
     7     Test(int i,char c,int* p)
     8         :i(998),c('Q'),p(new int(9999)){}
     9     ~Test(){delete p;}
    10 };

      有三个private的成员变量。该类型的对象在内存中的分布应该是这样的:

      占12个字节,其中5-8字节三个字节是为了对其后边int*变量,不存放数据。

      分析完了内存分布,获取对象的地址也很方便,于是就可以用指针拿数据了。

     1 int main()
     2 {
     3     Test t(1,2,NULL);
     4     cout << *(int*)&t << endl;
     5     cout << *((char*)&t+4) << endl;
     6     //(int*)&t+2拿到p对应的内存地址
     7     //解应用拿到p的值
     8     //在将p转换成int*,解应用拿到堆中数据。
     9     cout << *(int*)(*((int*)&t+2)) << endl;
    10     //最后一步也可以不进行两次转换
    11     //但是需要用二级指针
    12     //cout<< **((int**)&t+2) << endl;
    13 }

      输出结果:

      998
      Q
      9999

      与构造函数保持了一致。

      所以c++的私有成员变量,根本就不私有嘛。= =!

  • 相关阅读:
    Longest Valid Parentheses
    Gas Station
    Multiply Strings
    LeetCode:Merge Sorted Array
    LeetCode:Single Number II
    LeetCode: Single Number
    LeetCode:3Sum
    LeetCode:Binary Tree Preorder Traversal
    LeetCode: Best Time to Buy and Sell Stock III
    LeetCode: Best Time to Buy and Sell Stock II
  • 原文地址:https://www.cnblogs.com/ittinybird/p/4436503.html
Copyright © 2011-2022 走看看