何时使用静态成员函数? [英] When to use static member function?
本文介绍了何时使用静态成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复项:
C ++:静态成员函数
什么时候在C ++中使用静态成员函数?
When is it appropriate to use a static member function in C++? Please give me a real world example.
推荐答案
静态成员函数的良好用途:
Good uses of static member functions:
- 元编程。现实世界的例子是模板std :: char_traits。所有成员函数都是静态的
- 使它成为一个静态成员函数,它可以访问类的私有成员,虽然这里的朋友也可以。
- 因此,受保护的静态成员函数只能由其派生的类和类访问。
请注意,最后一种情况适用于受保护静态成员函数,但不是私人成员函数。在后一种情况下,你只需将它放入类的编译单元,将其隐藏为实现细节。
Note that the last case applies to a protected static member function but not a private one. In the latter case you would just put it into the compilation unit of the class, hiding it away as an implementation detail. For a protected one though you want it to be visible, albeit in a restricted way.
一个典型的例子是欺骗缺乏友谊的继承。
A typical case of that one is "cheating" the lack of inheritance of friendship.
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
}
这篇关于何时使用静态成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文