私有静态方法是否有必要? [英] Is there a Necessity for private static Methods?
问题描述
我上一家公司的主管工程师的规定是私人
static
方法应该作为实现文件中的函数实现,而不是作为类方法实现。
不要忘记他的规则是否有任何例外。我在当前的工作中偶然发现了它的动机:如果所讨论的函数的参数或返回类型是需要在头文件中包含定义文件的对象,这可能会造成不必要的困难。 em>
这足以让我避免使用私人
静态 code>方法再次,但是在我写出它们之前,我想知道是否有人知道一个利基,他们填写执行文件函数不会?
编辑:
这里有个例子可能会有所帮助。假设这是类Foo
的声明的开始,它有其他方法可以调用 void foo()
in执行档:
class Foo {
static void foo();
因此 foo
只能通过其他方法访问 Foo
。为什么我不能在实现文件中定义 foo
,并将它们一起放在标题之外?
成员函数可以访问类的所有 private
成员。如果一个功能需要访问这些成员,它应该是一个成员。无论它是否为 static
。
A static
函数是不对特定对象进行操作的函数。但是,它仍然可以接收对象作为参数。例如:
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;
$ b 使函数 static
是参数的顺序。例如, print
:
class A
{
int m;
static void print(std :: ostream& stream,A x,int options)
{
stream<< 价值是:<< (x.m * 1000000 + options);
}
}
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?
解决方案 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);
}
}
这篇关于私有静态方法是否有必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!