这纯粹是一个理论问题,我知道如果有人声明私有方法,你可能不应该调用它.我设法调用私有虚方法并更改实例的私有成员,但我无法弄清楚如何调用私有非虚方法(不使用__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)
#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)
如果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
| 归档时间: |
|
| 查看次数: |
34312 次 |
| 最近记录: |