静态成员函数 [英] Static member functions

查看:277
本文介绍了静态成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读sbi和Eli Bendersky在这个问题我开始想知道什么是静态成员函数。



类的朋友自由函数应该不能做任何一个静态成员函数可以做什么?

解决方案

一般情况下:



需要访问私有成员



static成员函数可以访问类的私有成员。如果需要,可以使用静态成员函数。你必须在标题中声明它,让它访问,所以你可以使它成为一个成员,而不是一个朋友。对于具有作为singleton的getInstance()方法的单例,以及使用静态工厂方法createInstance()的类来确保它们在堆上创建,通常这样做。这两个都需要访问私有构造函数。



元编程



静态成员函数非常适合模板元编程,你可以传入一个类并调用它的方法,而不知道在调用什么函数实际上会被调用的点。这通常被称为编译时多态性并且是元编程的重要部分。 std :: char_traits基于这个原则。



受限访问



共同使用私有静态成员函数,只是使它只能由类访问,并且本身不需要访问私有成员,不是很好地使用静态成员函数,因为它是实现细节的一部分类,而这在编译单元的匿名命名空间中是更好的。



然而,如果静态成员函数 protected

朋友函数






$ b

  • 可以访问私有成员,但需要在头中声明。

  • 可以在元编程中用作重载但仍需要在标头中声明。 (常见示例是 operator

  • 不会像您在此处做的那样,限制对方法的访问,而不是呼叫可访问的方式。


After reading sbi and Eli Bendersky's answers in this question I started to wondering what static member functions are for.

A class' friend free function shouldn't be able to do anything a static member function can do? If so, why/when should I prefer a static member function to a friend free one?

解决方案

In general:

Require access to private members

static member functions have access to private members of the class. If you need that, you can use a static member function. You have to declare it in the header anyway to give it access, so you may as well make it a member rather than a friend. It is commonly done this way for singletons that have a getInstance() method as singleton, and classes that use a static factory method createInstance() to ensure they are created on the heap. Both of these need access to the private constructor.

Meta-programming

static member functions are very good for template meta-programming where you can pass in a class and call its method without knowing at the point of call what function will actually get invoked. This is commonly called "compile-time polymorphism" and is an important part of meta-programming. std::char_traits is based on this principle.

Restricted access

The common use of a private static member function, just so that it can be accessed only by the class, and does not itself need access to private members, is not a good use of static member functions because it is part of the implementation detail of the class, and this is better done in the anonymous namespace of the compilation unit.

However if the static member function is protected it has use as it can get called by derived classes but not by external classes.

friend functions

  • Can have access to private members but need to be declared in the header anyway.
  • Can be used in meta-programming as part of an "overload" however still needs to be declared in the header. (Common example is operator<<)
  • Does not work for protected access with friendship as what you are trying to do here is restrict access to the method, not what the call has access to.

这篇关于静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆