Calling private method in C++

后端 未结 12 2214
忘了有多久
忘了有多久 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: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 
    
    #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;
    }
    

提交回复
热议问题