in C# I created a static class which had a number of mathematical helper functions I could call directly without creating an instance of the class. I cannot seem to get this to work in C++.
For example, if the class is called MathsClass and has a function called MultiplyByThree then I would use it like this:
float Variable1 = MathsClass.MultiplyByThree(Variable1);
In the C++ version of my code I am getting the errors:
'MathsClass' : illegal use of this type as an expression
and
error C2228: left of '.MultiplyByThree' must have class/struct/union
How would I write the C++ equivalent of the C# static class to give this kind of functionality?
The easy answer is to use the
::operator instead of the.operator:But in C++, free functions are generally preferred over static class functions, unless you have a specific reason to put them in a class. For keeping them together, and not polluting the global namespace, you can put them in their own namespace:
In Math.h
In Math.cpp:
And to use it:
Even better, make it a template and the same code will work for floats, doubles, ints, complex, or any type that has
operator*defined:In Math.h
The only issue being that you can’t separate the definition into math.cpp, it has to be in the header.