Best design for code used in many classes
-
Dear all,
In a project I've defined many a class, each in its own header and source file. I'd like to define still a few functions, which do not belong to any of the classes, but might be used in all classes (for example, we can imagine that functions as max(), min(), swap() etc could be used in many situations). I think it a stupid methode to define these functions in all classes, not to mention that so many "copy and paste" is not in line with object oriented design / code reuse. What's the best design to realize this?
Weichao -
@Weichao-Wang Hi,
You have several possibilities. You can define static function in a h file, you can wrap these functions in a class or a namespace, or let them global in the h fileHere is an example using a class
//tools.h class Tools{ static int max(int a, int b){ return a > b ? a : b; } }; //Call from another file in the project... #include "tools.h" ... int test = Tools.max(1, 2);
or without class:
//tools.h static int max(int a, int b){ return a > b ? a : b; } //Call from another file in the project... #include "tools.h" ... int test = max(1, 2);