Calling private method in C++

后端 未结 12 2157
忘了有多久
忘了有多久 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:56

    Followup on T.E.D.'s answer: Don't edit the header. Instead create your own private copy of the header and insert some friend declarations in that bogus copy of the header. In your source, #include this bogus header rather than the real one. Voila!

    Changing private to public might change the weak symbols that result from inlined methods, which in turn might cause the linker to complain. The weak symbols that result from inline methods will have the same signatures with the phony and real headers if all that is done is to add some friend declarations. With those friend declarations you can now do all kinds of evil things with the class such as accessing private data and calling private members.

    Addendum
    This approach won't work if the header in question uses #pragma once instead of a #include guard to ensure the header is idempotent.

提交回复
热议问题