在 C 中调用私有方法

新手上路,请多包涵

这纯粹是一个理论问题,我知道如果有人将方法声明为私有,您可能不应该调用它。我设法调用私有虚拟方法并更改实例的私有成员,但我不知道如何调用私有非虚拟方法(不使用 __asm )。有没有办法获得指向方法的指针?还有其他方法吗?

编辑:我不想更改类定义!我只想要一个黑客/解决方法。 :)

原文由 Luchian Grigore 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 584
2 个回答

#include 头文件,但是:

 #define private public
#define class struct

显然,您需要绕过各种包含保护等,并在一个独立的编译单元中执行此操作。

编辑:仍然是hackish,但不那么:

 #include <iostream>

#define private friend class Hack; private

class Foo
{
public:
    Foo(int v) : test_(v) {}
private:
    void bar();
    int test_;
};
#undef private
void Foo::bar() { std::cout << "hello: " << test_ << std::endl; }

class Hack
{
public:
    static void bar(Foo& f) {
        f.bar();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo f(42);
    Hack::bar(f);
    system("pause");
    return 0;
}

原文由 Pete 发布,翻译遵循 CC BY-SA 3.0 许可协议

调用私有方法的最简单方法(基于以前的答案,但更简单一些):

 // Your class
class sample_class{
    void private_method(){
        std::cout << "Private method called" << std::endl;
    }
};

// declare method's type
template<typename TClass>
using method_t = void (TClass::*)();

// helper structure to inject call() code
template<typename TClass, method_t<TClass> func>
struct caller{
    friend void call(){
        TClass obj;
        (obj.*func)();
    }
};

// even instantiation of the helper
template struct caller<sample_class,&sample_class::private_method>;

// declare caller
void call();

int main(){
    call(); // and call!
    return 0;
}

原文由 Gleb Bezborodov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题