简体   繁体   English

如何违反封装属性?

[英]How can I Violate Encapsulation property?

How can I Violate Encapsulation property without having a compile time error? 如何在没有编译时错误的情况下违反Encapsulation属性? (in C++) (在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. 但是,要使用它们,您将需要修改具有私有成员的类-此时,根据情况,仅将一些方法从private重新定义为protectedpublic可能更简单。

You don't get to*. 你不会*。 Encapsulation is a feature of C++. 封装是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. 这当然不能保证有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM