首页 > 解决方案 > 使用 C++ 破解私有数据

问题描述

澄清:这个问题最初来自我想到的一个挑战,与实际系统的编程无关。

假设我有一个类,我知道它的架构是我无法更改的,并且我不想继承它,但我确实想访问它的私有数据和功能。我该怎么做?

假设我的班级看起来像这样:

class A {
public:
    int v = 89;

private:
    int a = 5;
    virtual void function(int a, int b) {
        cout << a << " " << b << endl;
    }
};

标签: c++reinterpret-cast

解决方案


不久前在这个博客上偶然发现了一个巧妙的模板技巧: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;
}

推荐阅读