简体   繁体   English

如何直接访问 class 的私有成员?

[英]How to access private members of a class directly?

I had a homework which i was asked how to access private members of a class and modify them in c++.I searched about it and i found out that we can do it with typecast and pointers which i know it's an undefined behavior and it should never be used.My question is: Is it possible to do such thing in other object oriented languages like java or python?我有一个作业,有人问我如何访问 class 的私有成员并在 c++ 中修改它们。我搜索了它,我发现我们可以使用类型转换和指针来完成它,我知道这是一个未定义的行为,它不应该我的问题是:是否可以在其他面向 object 的语言(如 java 或 python)中做这样的事情?

The C++ programming language has a friend specifier . C++ 编程语言有一个friend说明符 Friend function can see its friend class' private members.好友 function 可以看到其好友类的私有成员。 But more young languages don't include this mechanism.但是更多的年轻语言不包括这种机制。 Because the mechanism isn't correct for object oriented programming paradigm(for encapsulation).因为该机制不适用于面向 object 的编程范式(用于封装)。

In C++ you can write a member function that can access and modify private members and make such function public.在 C++ 中,您可以编写一个成员 function 可以访问和修改私有成员并将此类 function 公开。 This is a common way for OOP.这是OOP的常用方式。 However, of course, different languages including C++ may provide hax to modify protected members in another way.但是,当然,包括 C++ 在内的不同语言可能会提供 hax 以另一种方式修改受保护的成员。

class T {
public:
  int get() const {
    return _member;
  } 
  void set(int member) {
    _member = member;
  } 
protected:
  int _member;

};

List of well-known hacks知名黑客列表

You can easily access any member in Python.您可以轻松访问 Python 中的任何成员。 Just dir whatever you what to hack.只需dir无论您要破解什么。 Private members in Python . Python 中的私人成员

You can hack C++ members with template http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html .您可以使用模板http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.ZFC35FDC70D5FC69D269883A82EZ7破解 C++ 成员。 It is much safer than use pointers.它比使用指针安全得多。

You can access private members via reflection in Java https://docs.oracle.com/javase/tutorial/reflect/ .您可以通过 Java https://docs.oracle.com/javase/tutorial/reflect/中的反射访问私有成员。

Generally, any language that lets you debug the code should also reveal somehow protected variables.通常,任何允许您调试代码的语言也应该以某种方式显示受保护的变量。

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

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