可以通过“指针+偏移量”的方式访问私有变量。

    1. #include <iostream>
    2. using namespace std;
    3. class Test
    4. {
    5. private:
    6. int a;
    7. int b;
    8. public:
    9. Test(int _a, int _b){a=_a; b=_b;}
    10. void Print(){
    11. cout << this->a << ", " << this->b << endl;
    12. }
    13. };
    14. int main() {
    15. Test a(3, 3);
    16. a.Print();
    17. int *p = (int*)&a;
    18. *p = 10;
    19. a.Print();
    20. *(p+1) = 11;
    21. a.Print();
    22. return 0;
    23. }

    运行结果:
    image.png

    困惑:不同类型的成员变量的偏移量应该怎么计算

    1. #include <iostream>
    2. using namespace std;
    3. class TestA
    4. {
    5. private:
    6. int a;
    7. int b;
    8. public:
    9. TestA(int _a, int _b){a=_a; b=_b;}
    10. void Print() const{
    11. cout << this->a << ", " << this->b << endl;
    12. }
    13. };
    14. class TestB
    15. {
    16. private:
    17. short a;
    18. int b;
    19. float c;
    20. double d;
    21. char e;
    22. public:
    23. TestB(short _a, int _b, float _c, double _d, char _e){a=_a; b=_b; c=_c; d=_d; e=_e;}
    24. void Print() const{
    25. cout << this->a << ", " << this->b << ", " << this->c << ", " << this->d << ", " << this->e << endl;
    26. }
    27. void PrintAddress() const {
    28. cout << &a << ", " << &b << ", " << &c << ", " << &d << ", " << &e << endl;
    29. }
    30. };
    31. int main() {
    32. TestA ta(3, 3);
    33. ta.Print();
    34. int* p = (int*)&ta;
    35. *p = 4;
    36. ta.Print();
    37. *(p+1) = 5;
    38. ta.Print();
    39. cout << "------------------" << endl;
    40. // 或者使用reinterpret_cast加字节偏移量
    41. char ch = 'e';
    42. TestB tb(13, 13, 13.0, 13.0, ch);
    43. cout << &tb <<endl;
    44. tb.PrintAddress();
    45. tb.Print();
    46. auto q1 = reinterpret_cast<short *>((char*)(&tb));
    47. *q1 = 14;
    48. tb.Print();
    49. auto q2 = reinterpret_cast<int *>((char*)(&tb) + 4);
    50. *q2 = 15;
    51. tb.Print();
    52. auto q3 = reinterpret_cast<float *>((char*)(&tb) + 2*4);
    53. *q3 = 16;
    54. tb.Print();
    55. auto q4 = reinterpret_cast<double *>((char*)(&tb) + 4*4);
    56. *q4 = 17;
    57. tb.Print();
    58. auto q5 = reinterpret_cast<char *>((char*)(&tb) + 6*4+1);
    59. *q5 = 'f';
    60. tb.Print();
    61. cout << sizeof(short*) << sizeof(int*) << sizeof(float*) << sizeof(double*) << sizeof(char*) << endl;
    62. cout << sizeof(short) << sizeof(int) << sizeof(float) << sizeof(double) << sizeof(char) << endl;
    63. return 0;
    64. }

    运行结果:

    1. D:\jetbrains\cpp\untitled\cmake-build-debug\untitled.exe
    2. 3, 3
    3. 4, 3
    4. 4, 5
    5. ------------------
    6. 0x61fdc0
    7. 0x61fdc0, 0x61fdc4, 0x61fdc8, 0x61fdd0, e
    8. 13, 13, 13, 13, e
    9. 14, 13, 13, 13, e
    10. 14, 15, 13, 13, e
    11. 14, 15, 16, 13, e
    12. 14, 15, 16, 17, e
    13. 14, 15, 16, 17, e
    14. 88888
    15. 24481
    16. Process finished with exit code 0