是否可以访问类的私有成员?
是否可以在 C++ 中访问类的私有成员。
如果你没有朋友 功能并且您无权访问 类定义
Is it possible to access private members of a class in c++.
provided you don't have a friend
function and You don't have access to
the class definition
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的意思是使用一些指针算术来获得访问权限? 这是可能的,但绝对是危险的。 另请看一下这个问题:访问私有成员
You mean using some pointer arithmetic to gain the access ? It is possible but is definitely dangerous. Take a look at this question also: Accessing private members
我认为有一些像这样的老派技巧:
但是强烈不建议您这样做(我很快就读到了 C++ 标准中关于此的内容) - 如果您想阅读更多有关此 google 的“#define”私人公共”
I think there was some old school trick like this:
But you are strongly discouraged to do this (I've read quickly that the said something about this in the C++ standard) - if you want to read more about this google for "#define private public"
好吧,我可能在说垃圾,但我认为你可以尝试定义一个“双胞胎”类,其成员与你想要修改的类相同,但具有不同的公共/私有修饰符,然后使用reintepret_cast将原始类转换为你的类可以访问私有成员。
它有点 hacky ;-)
一些代码来解释这个想法:
以及代码中的某个地方:
编辑:就像之前有人写过的那样,这可能有效,但标准不保证具有 public 和 private 修饰符的变量的顺序将会是一样的
Well I might be talking rubish, but I think you could try to define a "twin" class with same members as the class you want to modify but different public/private modifiers and then use reintepret_cast to cast the original class to yours in which you can access the private members.
Its a bit hacky ;-)
A bit of code to explain the idea:
and somewhere in the code:
edit: so like someone already wrote before, this might work but the standard does not guarantee the order of the variables with public and private modifier will be the same
即使可以通过一些令人讨厌的黑客来实现 - 请参阅之前的帖子 - 你应该
不这样做。
封装的存在有一个很好的目的,将类成员设置为私有意味着开发人员不希望任何人乱搞该成员。 这应该意味着
“您不必访问此成员即可充分使用公共接口”
Even if it were possible through some nasty hack - see earlier posts - you SHOULD
not do it.
Encapsulation exists for a very good purpose, and setting class member as private means that the developer did not intend anyone to mess around with that member. That should mean
"You don't have to access this member in order to use the public interface to it's full intended extent"