你在哪里使用一个朋友函数和一个静态成员函数? [英] Where would you use a friend function vs. a static member function?

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

问题描述

当我们希望它访问该类的私有成员时,我们使非成员函数成为类的朋友。这给它与静态成员函数具有相同的访问权限。这两个选择都会给你一个函数,不与该类的任何实例相关联。



什么时候必须使用friend函数?我们什么时候必须使用静态函数?如果两者都是解决问题的可行选择,我们如何权衡它们的适用性?例如,当实现一个工厂创建类的实例 foo 它只有一个私有构造函数,如果工厂函数是 foo 的静态成员(你会调用 foo :: create() create_foo())?

解决方案

第11.5节C ++编程语言由Bjarne Stroustrup声明,普通成员函数获得3件事:



  1. 必须在实例上调用

  2. / ol>

    朋友只能获得1个。



    static 函数获取1和2。


    We make a non-member function a friend of a class when we want it to access that class's private members. This gives it the same access rights as a static member function would have. Both alternatives would give you a function that is not associated with any instance of that class.

    When must we use a friend function? When must we use a static function? If both are viable options to solve a problem, how do we weigh up their suitability? Is there one that should be preferred by default?

    For example, when implementing a factory that creates instances of class foo which only has a private constructor, should that factory function be a static member of foo (you would call foo::create()) or should it be a friend function (you would call create_foo())?

    解决方案

    Section 11.5 "The C++ Programming Language" by Bjarne Stroustrup states that ordinary member functions get 3 things:

    1. access to internals of class
    2. are in the scope of the class
    3. must be invoked on an instance

    friends get only 1.

    static functions get 1 and 2.

    这篇关于你在哪里使用一个朋友函数和一个静态成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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