C++ Class Extension

前端 未结 9 1202
既然无缘
既然无缘 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:45

    You cannot add methods or data physically to the class file which is in binary form. However, you can add methods and data (functionality and state) to the objects of that class by writing extension classes. This is not straight forward and requires Meta-Object-Protocol and Interface based programming. You need to do a lot to achieve this in C++ since it does not support Reflection out of the box. In such an implementation when you query for the interface implemented by your new extension class via the original class object pointer, the meta object implementation returns that interface pointer via the meta class object for the extension class that it creates at runtime. This is how many customizable (plugin based) software application frameworks work. However, you must remember that it requires many other MOP mechanisms to be written to instanciate meta objects for all the classes using dictionaries in which the object relations are described and give the correct interface pointers for the original and extended class objects. Dassault Systemes' CATIA V5 is written in such an architecture called CAA V5 where you can extend existing components by writing new extension classes with the desired functionality.

    0 讨论(0)
  • 2020-12-11 03:48

    Sorry, no. Once your code is in obj, you can not change it. If this can be done in VC partial classes would be supported already. There is one exception though, operator methods can be extended using global functions, pretty like how cout<< is implemented in STL.

    0 讨论(0)
  • 2020-12-11 03:53

    There is one way in which it can be done. And that's by relaxing your requirements a bit. In C++, people often say that the interface of a class consists not just of its member functions, but of all functions that work on the class.

    That is, non-member functions which can be given the class as a parameter should be considered part of its interface.

    For example, std::find() or std::sort() are part of the interface of std::vector, even though they aren't members of the class.

    And if you accept this definition, then you can always extend a class simply by adding nonmember functions.

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