Calling private method in C++

后端 未结 12 2124
忘了有多久
忘了有多久 2020-11-27 20:02

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 chang

相关标签:
12条回答
  • 2020-11-27 20:36

    You have friend classes and functions.

    I know that if someone declares a method private, you probably shouldn't call it.

    The point is not 'you shouldn't call it', it's just 'you cannot call it'. What on earth are you trying to do?

    0 讨论(0)
  • 2020-11-27 20:39

    The simplest way:

    #define private public
    #define protected public
    
    0 讨论(0)
  • 2020-11-27 20:41

    #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.

    EDIT: 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;
    }
    
    0 讨论(0)
  • 2020-11-27 20:41

    I think the closest you'll get to a hack is this, but it's not just unwise but undefined behaviour so it has no semantics. If it happens to function the way you want for any single program invocation, then that's pure chance.

    0 讨论(0)
  • 2020-11-27 20:45

    Call the private method from a public function of the same class.

    0 讨论(0)
  • 2020-11-27 20:45

    For GCC it can be done by using mangled name of a function.

    #include <stdio.h>
    
    class A {
    public:
        A() {
            f(); //the function should be used somewhere to force gcc to generate it
        }
    private:
        void f() { printf("\nf"); }
    };
    
    typedef void(A::*TF)();
    
    union U {
        TF f;
        size_t i;
    };
    
    int main(/*int argc, char *argv[]*/) {
        A a;
        //a.f(); //error
        U u;
        //u.f = &A::f; //error
    
        //load effective address of the function
        asm("lea %0, _ZN1A1fEv"
        : "=r" (u.i));
        (a.*u.f)();
        return 0;
    }
    

    Mangled names can be found by nm *.o files.

    Add -masm=intel compiler option

    Sources: GCC error: Cannot apply offsetof to member function MyClass::MyFunction https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html

    0 讨论(0)
提交回复
热议问题