我的程序:
#include <stdio.h>
class a
{
private:
int k;
public:
int readk() { return k; }; //测试用
};
main()
{
a a1,*p;
p=&a1;
*(int *)p=100; //设a1.k=100
printf("%d\n",a1.readk());
}
//在VC/BCB/GCC下通过
方法1:
a a1;
*(int*)&a1 = 100;
方法2:
#define private public
……
a a1;
a1.k = 100;
class test
{
public:
test(){k =5;}
private:
int k;
};
main()
{
test tt;
int * k = (int*)(void*)&tt;
printf("%d",*k);
}
class A
{
private:
int m_a;
};
int main()
{
A a;
int* p = (int*)&a;
*p = 4;
return 0;
}
?
宏有点变态.再给一个比较直观的方法.
class a
{
private:
int k;
};
class b
{
public:
int k;
};
a aa;
b *bb = reinterpret_cast<b*>(&aa);
#include <iostream.h>
class A
{
private:
int k;
int l;
int m;
int n;
public:
printk() {printf("%c\n", k);}
printl() {printf("%c\n", l);}
printm() {printf("%c\n", m);}
printn() {printf("%c\n", n);}
};
int main(int argc, char* argv[])
{
A cd;
int *p = (int*)&cd;
*p = 'k';
cd.printk();
p = (int*)&cd + 1;
*p = 'l';
cd.printl();
p = (int*)&cd + 2;
*p = 'm';
cd.printm();
p = (int*)&cd + 3;
*p = 'n';
cd.printn();
return 0;
}