关键是熟悉内存分布
#include <iostream>
using namespace std;
class A{
private:
int i;
public:
void printa()
{
printf("%d\n",i);
}
};
class B{
private:
A a;
};
int main()
{
B b;
A* aa=(A*)&b;
int* ii=(int*)aa;
*ii=100;
aa->printa();
return 0;
}
100
妈的!太变态!!
#include <iostream>
using namespace std;
class A{
private:
int i;
public:
void printa()
{
printf("%d",i);
}
};
class B{
private:
int j1;
A a;
int j2;
public:
void printb()
{
printf("%d\n",j1);
}
};
int main()
{
B b;
int *jj=(int*)&b;
*jj=100;
b.printb();
return 0;
}
得到100
#include <iostream>
using namespace std;
class A{
private:
int i;
public:
void printa()
{
printf("%d\n",i);
}
};
class B{
private:
A a;
int j;
public:
void printb()
{
printf("%d\n",j);
}
};
int main()
{
B b;
A* aa=(A*)&b;
int* ii=(int*)aa;
*ii=100;
aa->printa();
int*jj=(int*)aa+1;//为什么是1呢?我用sizeof(A)是错的
*jj=200;
b.printb();
return 0;
}
100
200
#include <iostream>
using namespace std;
class A{
private:
int i;
public:
void printa()
{
printf("%d\n",i);
}
};
class B{
private:
A a;
int j;
public:
void printb()
{
printf("%d\n",j);
}
};
int main()
{
B b;
A* aa=(A*)&b;
int* ii=(int*)aa;
*ii=100;
aa->printa();
int*jj=(int*)aa+1;
*jj=200;
b.printb();
char *jj2=(char*)&b+sizeof(A);//这样才能用sizeof(A)
*jj2=300;//这里解完地址后,用的是char,最大255,300超出了范围.只取有效的部分,就是44
b.printb();
int *jj3=(int*)jj2;
*jj3=400;
b.printb();
return 0;
}
100
200
44
400