旅途

如果想飞得高,就该把地平线忘掉

类的不安全性在于可通过类的指针访问类的成员

我的程序:
#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;
}

posted on 2007-09-04 00:32 旅途 阅读(135) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理