How can I Violate Encapsulation property?
How can I Violate Encapsulation property without having a compile time error? (in C++)
just so curious..
This was actually a question asked by one of my professor.. Please don't misunderstand. This was asked when we had 开发者_开发问答a discussion over compiler error's
#define private public
#define protected public
#define class struct
There you go :-)
I'm going to assume that by "violating encapsulation" you mean "accessing private members from outside a class".
The only way to do this "legally" that I know is using friend classes / methods.
However, in order to use them you will need to modify the class which has private members - at which point it might be simpler to just redefine some methods from private
to protected
or public
, depending on the case.
You don't get to*. Encapsulation is a feature of C++.
**unless you do something dark, evil, and magic.*
You change the headers defining the classes in question to make the desired members public. In other words, you remove the encapsulation. Don't do this.
Design a mirror class that has the same members as the class you are trying to access the nonpublic members of and hardcast an object of said class to the mirror class.
class original
{
private: int x,y,z;
public: int dosomething();
};
class mirror
{
public: int x,y,z;
};
int main()
{
original *o = new original;
mirror *m = (mirror*)o;
m->x = 10;
}
this of course is not guaranteed to work.
精彩评论