Ume*_* MS 14 c++ static function
可能的重复:
你在哪里使用朋友功能与静态功能?
C++:静态成员函数
什么时候在C++中使用静态成员函数是否合适?请给我一个真实世界的例子.
Cas*_*Cow 13
静态成员函数的良好用途:
请注意,最后一种情况适用于受保护的静态成员函数,但不适用于私有函数.在后一种情况下,您只需将其放入类的编译单元中,将其作为实现细节隐藏起来.对于受保护的,虽然您希望它是可见的,尽管是受限制的.
一个典型的案例是"欺骗"缺乏友谊的继承.
class B
{
friend class A;
// lots of private stuff
};
class A
{
protected:
static void callsSomePrivateMembers( B& b );
};
class AChild : public A
{
void foo( B& b );
}
void AChild::foo( B& b )
{
// AChild does not have private access to B as friendship is not inherited
// but I do have access to protected members of A including the static ones
callsSomePrivateMembers( b ); // get to call them through a back-door
}
Run Code Online (Sandbox Code Playgroud)
使用它的自然地方是当你不能使用自由函数时,因为你需要访问类的内部.最典型的例子是构建函数,如下所示.Foo的构造函数是私有的,以确保它不是以构造函数之外的任何其他方式构造的.
#include <iostream>
class Foo {
public:
static Foo* createFoo() {return new Foo();}
private:
Foo() {}
};
int main() {
//Foo nonBuiltFoo; //wont compile
Foo* freshFoo = Foo::createFoo();
delete freshFoo;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这种情况的典型用法是前面提到的Singleton模式.当您不必访问类的受保护和私有部分时,不需要静态成员函数(可以使用自由函数),但是当它在类的域内时,也有一些使用静态成员函数但不是restricted/logical在单个实例上使用该函数.