转载:http://blog.sina.com.cn/s/blog_53d8668901000cmb.html
C++对象中的私有(保护)成员变量也可以从对象外面访问。下面的代码会让你大吃一惊:
#include <iostream.h>
class TestClass{
private:
int a;
char b;
public:
char c;
TestClass(): a(29), b('b'), c('c'){ }
};
void main(void)
{
TestClass* pObject = new TestClass();
int *p_int_a = (int*)pObject;
cout <<"The value of pointer p_int_a is: " << *p_int_a++ << endl;
char *p_char_b = (char*)p_int_a;
cout << "The value of pointer p_char_b is: " << *p_char_b++ << endl;
cout << "The value of pointer p_char_b is: " << *p_char_b << endl;
}
输出结果为:
The value of pointer p_int_a is: 29
The value of pointer p_char_b is: b
The value of pointer p_char_b is: c
请按任意键继续. . .
为什么会这样?原因很简单:在C++中,private, protected只是程序逻辑上的一种保护,
即如果破坏了这种规则(从对象外面访问private,protected成员),只是在编译器哪儿通不过。
但通过指针可以直接读取对象中的私有变量,当然,前提是知道对象中成员变量的顺序和类型,否则读取的数据与我们需要的有偏差!
扩展阅读:http://blog.youkuaiyun.com/sandyzhs/article/details/4093332