在C++中调用私有方法

Luc*_*ore 17 c++

这纯粹是一个理论问题,我知道如果有人声明私有方法,你可能不应该调用它.我设法调用私有虚方法并更改实例的私有成员,但我无法弄清楚如何调用私有非虚方法(不使用__asm).有没有办法获得指向该方法的指针?有没有其他方法可以做到这一点?

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

Joh*_*itb 13

我的博文.我在这里重新发布代码

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;
Run Code Online (Sandbox Code Playgroud)

有些私人会员

struct A {
private:
  void f() {
    std::cout << "proof!" << std::endl;
  }
};
Run Code Online (Sandbox Code Playgroud)

以及如何访问它们

struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;

int main() {
  A a;
  (a.*result<Af>::ptr)();
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*ete 9

#include 头文件,但是:

#define private public
#define class struct
Run Code Online (Sandbox Code Playgroud)

显然,你需要绕过各种包含保护等,并在一个独立的编译单元中完成.

编辑:仍然是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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我'上课'{void f(){}};`怎么办? (9认同)
  • 这太脏了,我的眼睛正在流血XD (8认同)
  • 这些重新定义渲染整个程序UB,严格来说你已经改变了类型声明.写"朋友"几乎不是黑客. (7认同)
  • **重新定义关键字会调用未定义的行为**. (4认同)
  • 谁给我-1了?- OP说这纯粹是理论上的! (2认同)

Naw*_*waz 5

如果public函数返回函数的地址private,则可以调用它,然后任何人都可以使用该地址来调用私有函数.

例,

class A
{
   void f() { cout << "private function gets called" << endl; }
 public:
     typedef void (A::*pF)();
     pF get() { return &A::f; }
};

int main() 
{
        A a;
        void (A::*pF)() = a.get();
        (a.*pF)(); //it invokes the private function!
}
Run Code Online (Sandbox Code Playgroud)

输出:

private function gets called
Run Code Online (Sandbox Code Playgroud)

在ideone上演示:http://www.ideone.com/zkAw3

  • 如果我可以声明函数get(),为什么不从它调用f? (2认同)