在C ++中调用私有方法 [英] Calling private method in C++

查看:112
本文介绍了在C ++中调用私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is purely a theoretical question, I know that if someone declares a method private, you probably shouldn't call it. I managed to call private virtual methods and change private members for instances, but I can't figure out how to call a private non-virtual method (without using __asm). Is there a way to get the pointer to the method? Are there any other ways to do it?

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

I don't want to change the class definition! I just want a hack/workaround. :)

推荐答案

#include 头文件, p>

#include the header file, but:

#define private public
#define class struct

显然,你需要解决各种包含保护等问题,并在一个单独的编译单元中进行。

Clearly you'll need to get around various inclusion guards etc and do this in an isolated compilation unit.


仍然有hackish,但较少:

Still hackish, but less so:

#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;
}

这篇关于在C ++中调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆