Possible Duplicate:
Is it possible to access private members of a class?
Is it possible to change PRIVATE data memebers of a CLASS without Member function or Friend function,by creating object of that class and accessing address of that created object,is it possible to some how modify PRIVATE data members using such POINTERS if we know the address of that class???
Assuming you know the in-memory layout of the class fields, it is indeed possible to change its private members using something like *((FieldType*)((char*)&object + fieldOffset)) = someValue;
.
You shouldn't do this. It's criminal.
The language is not there to police you but rather to keep you from making mistakes. You can do a set of different things to gain access to the private fields, but at the end of the day, none of them is a good idea on the premise that if the class is yours, you can provide access in a sensible way, and if it is not yours, all private members are implementation details that can change from one version to another and there are most probably invariants of the class that you might or not know and could break if you modify those members.
精彩评论