C++ Class Extension

前端 未结 9 1217
既然无缘
既然无缘 2020-12-11 03:22

Is there a way to add new methods to a class, without modifying original class definition (i.e. compiled .lib containing class and corresponding .h file) like C#\'s class ex

9条回答
  •  星月不相逢
    2020-12-11 03:34

    Generally not. However, if the library does not create instances of the class that require your extension and you are able to modify all places in the app that create an instance of the class and require your extensions, there is a way you can go:

    • Create a factory function that is called at all places that require an instance of the class and returns a pointer to the instance (google for Design Patterns Factory, ...).
    • Create a derived class with the extensions you want.
    • Make the factory function return your derived class instead of the original class.

    Example:

    
        class derivedClass: public originalClass { /* ... */};
    
        originalClass* createOriginalClassInstance()
        {
             return new derivedClass();
        }
    
    • Whenever you need to access the extensions, you need to cast the original cast to the derived class, of course.

    This is roughly how to implement the "inherit" method suggested by Glen. Glen's "wrapper class with same interface" method is also very nice from a theoretical point of view, but has slightly different properties that makes it less probable to work in your case.

提交回复
热议问题