c++ - 使用 C++ 破解私有数据
问题描述
澄清:这个问题最初来自我想到的一个挑战,与实际系统的编程无关。
假设我有一个类,我知道它的架构是我无法更改的,并且我不想继承它,但我确实想访问它的私有数据和功能。我该怎么做?
假设我的班级看起来像这样:
class A {
public:
int v = 89;
private:
int a = 5;
virtual void function(int a, int b) {
cout << a << " " << b << endl;
}
};
解决方案
不久前在这个博客上偶然发现了一个巧妙的模板技巧:http: //bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
不要在任何生产代码中使用它,这只是一个教育示例!!!
它基本上利用了在模板初始化的某些部分被忽略的“私有”
template<typename Tag>
struct result {
/* export it ... */
typedef typename Tag::type type;
static type ptr;
};
template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;
template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
/* fill it ... */
struct filler {
filler() { result<Tag>::ptr = p; }
};
static filler filler_obj;
};
template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;
用法:采用以下结构:
struct A {
private:
void f() {
std::cout << "proof!" << std::endl;
}
};
创建你的“强盗”
struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;
用它:
int main()
{
A a;
(a.*result<Af>::ptr)();
return 0;
}
推荐阅读
- azure - 如何在 HDInsight 上安装 Presto?
- mysql - 如果查询,则无法处理 Mysql 多个 else 的正确语法
- hadoop - 可以将 Hive 外部表位置创建到外部 hadoop 集群吗?
- python - 具有复杂路径的 Django urls 行为
- html - 在引导日期选择器中设置默认日期的问题
- javascript - 图像忽略来自 JavaScript 函数的“zIndex”指令
- android - 将APK转换为最小APK后如何解析?
- python - C++ 和 python 中的代码相同,但输出不同
- r - 如何使用ggplot在堆叠和分组条形图中显示值标签
- java - 将参数值从我的实现服务传递到我的 RestController java springboot