问题
The Principle Engineer at my last company had a rule that private
static
methods should be implemented as functions in the implementation file, not as class methods.
I don't remember if there were any exceptions to his rule. I have stumbled into the motivation for it at my current job: If the arguments or return type of the function in question are objects that would require the inclusion of a definition file in the header, this can cause unnecessary difficulties.
That's enough to steer me away from ever using a private
static
method again, but before I wrote them off I wanted to know if anyone is aware of a niche they fill that an implementation file function would not?
EDIT:
An example may be helpful here. Say this is the start of the declaration of class Foo
, which has other methods which will call void foo()
in the implementation file:
class Foo {
static void foo();
So foo
is only accessible by other methods of Foo
. Why wouldn't I just define foo
in the implementation file, and keep it out of the header all together?
回答1:
Member functions have access to all private
members of the class. If a function needs access to these members, it should be a member. This applies whether or not it's static
.
A static
function is one that doesn't operate on a specific object. However, it can still receive objects as parameters. For example:
class A
{
int m;
static int process_3_objects_in_some_way(A x, A y, A z)
{
return x.m + y.m + z.m;
}
}
Another reason to make a function static
is the order of parameters. For example, print
:
class A
{
int m;
static void print(std::ostream& stream, A x, int options)
{
stream << "Value is: " << (x.m * 1000000 + options);
}
}
回答2:
Unlike free-standing static
functions in the implementation file, private static member functions can be used in the header of the class. This is important in situations when you want to inline a non-private member function, which calls your private static function:
class Demo {
private:
static std::string sanitize(const std::string& name);
std::string name;
public:
Demo(const std::string& n) : name(sanitize(n)) {
}
};
Doing the same with free-standing static functions would require implementing Demo
's constructor in the cpp file.
回答3:
friend
functions or classes which are implemented in another implementation file are another example where a private static member function is required.
来源:https://stackoverflow.com/questions/41964745/is-there-a-necessity-for-private-static-methods