可以通过“指针+偏移量”的方式访问私有变量。
#include <iostream>
using namespace std;
class Test
{
private:
int a;
int b;
public:
Test(int _a, int _b){a=_a; b=_b;}
void Print(){
cout << this->a << ", " << this->b << endl;
}
};
int main() {
Test a(3, 3);
a.Print();
int *p = (int*)&a;
*p = 10;
a.Print();
*(p+1) = 11;
a.Print();
return 0;
}
运行结果:
困惑:不同类型的成员变量的偏移量应该怎么计算
#include <iostream>
using namespace std;
class TestA
{
private:
int a;
int b;
public:
TestA(int _a, int _b){a=_a; b=_b;}
void Print() const{
cout << this->a << ", " << this->b << endl;
}
};
class TestB
{
private:
short a;
int b;
float c;
double d;
char e;
public:
TestB(short _a, int _b, float _c, double _d, char _e){a=_a; b=_b; c=_c; d=_d; e=_e;}
void Print() const{
cout << this->a << ", " << this->b << ", " << this->c << ", " << this->d << ", " << this->e << endl;
}
void PrintAddress() const {
cout << &a << ", " << &b << ", " << &c << ", " << &d << ", " << &e << endl;
}
};
int main() {
TestA ta(3, 3);
ta.Print();
int* p = (int*)&ta;
*p = 4;
ta.Print();
*(p+1) = 5;
ta.Print();
cout << "------------------" << endl;
// 或者使用reinterpret_cast加字节偏移量
char ch = 'e';
TestB tb(13, 13, 13.0, 13.0, ch);
cout << &tb <<endl;
tb.PrintAddress();
tb.Print();
auto q1 = reinterpret_cast<short *>((char*)(&tb));
*q1 = 14;
tb.Print();
auto q2 = reinterpret_cast<int *>((char*)(&tb) + 4);
*q2 = 15;
tb.Print();
auto q3 = reinterpret_cast<float *>((char*)(&tb) + 2*4);
*q3 = 16;
tb.Print();
auto q4 = reinterpret_cast<double *>((char*)(&tb) + 4*4);
*q4 = 17;
tb.Print();
auto q5 = reinterpret_cast<char *>((char*)(&tb) + 6*4+1);
*q5 = 'f';
tb.Print();
cout << sizeof(short*) << sizeof(int*) << sizeof(float*) << sizeof(double*) << sizeof(char*) << endl;
cout << sizeof(short) << sizeof(int) << sizeof(float) << sizeof(double) << sizeof(char) << endl;
return 0;
}
运行结果:
D:\jetbrains\cpp\untitled\cmake-build-debug\untitled.exe
3, 3
4, 3
4, 5
------------------
0x61fdc0
0x61fdc0, 0x61fdc4, 0x61fdc8, 0x61fdd0, e
13, 13, 13, 13, e
14, 13, 13, 13, e
14, 15, 13, 13, e
14, 15, 16, 13, e
14, 15, 16, 17, e
14, 15, 16, 17, e
88888
24481
Process finished with exit code 0