我可以转换对象并访问C ++中的私有数据成员吗? [英] Can I transform an object and access the private data members in C++?

查看:112
本文介绍了我可以转换对象并访问C ++中的私有数据成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问类中的私有数据成员。类中没有成员函数来访问私有数据成员。它是私人的。

I want to access a private data member in a class. There is no member function in the class to access the private data member. It is private.

我想带这个类,以及一些如何破解它。一个方法是复制类的声明,使私有成员public,并调用新的类class something_else。然后我做一个重新解释铸造和复制原始的对象。这工作。但我想要更优雅的东西...或者通用...或者只是另一种方式。

I want to take the class and some how crack it open. One method was to copy the declaration of the class, make the private member public and call the new class class something_else. Then I do a reinterpret cast and copy the original object. This works. But I want something more elegant ... or perhaps generic ... or just another way.

有什么选择?我可以使用void *吗?我可以memcpy类的另一个空类吗?有什么办法做到这一点?

What options are there? Can I use void*? Can I memcpy the class into another empty class? What are ways to do this??

推荐答案

我假设


  1. 您已经通过了破解封装是糟糕的阶段,

  2. 耗尽其他可能的解决方案,

  3. 无法更改类的标题。

私人成员,如 GotW#76 中所示。


  1. 复制类定义并添加朋友声明。

  2. 使用邪恶的宏:<$ c $

  3. 编写一个具有相同二进制布局的类定义,并使用 reinterpret_cast 从原始类转换为假类。

  4. 如果有一个模板成员函数(唯一的可移植解决方案) li>
  1. Duplicate a class definition and add a friend declaration.
  2. Use evil macros: #define private public before including class' header.
  3. Write a class definition with identical binary layout and use reinterpret_cast to switch from original class to a fake one.
  4. Specialize a template member function if there is one (the only portable solution).

这篇关于我可以转换对象并访问C ++中的私有数据成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆