你在哪里使用一个朋友函数和一个静态成员函数? [英] Where would you use a friend function vs. a static member function?
问题描述
当我们希望它访问该类的私有成员时,我们使非成员函数成为类的朋友。这给它与静态成员函数具有相同的访问权限。这两个选择都会给你一个函数,不与该类的任何实例相关联。
什么时候必须使用friend函数?我们什么时候必须使用静态函数?如果两者都是解决问题的可行选择,我们如何权衡它们的适用性?例如,当实现一个工厂创建类的实例 foo
它只有一个私有构造函数,如果工厂函数是 foo
的静态成员(你会调用 foo :: create()$你应该调用
create_foo()
)?
第11.5节C ++编程语言由Bjarne Stroustrup声明,普通成员函数获得3件事:
- 必须在实例上调用
- / ol>
- access to internals of class
- are in the scope of the class
- must be invoked on an instance
朋友
只能获得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:
friend
s get only 1.
static
functions get 1 and 2.
这篇关于你在哪里使用一个朋友函数和一个静态成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!