Where would you use a friend function vs. a static member function?

后端 未结 15 2224
[愿得一人]
[愿得一人] 2020-12-02 04:56

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 w

15条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:38

    The standard requires that operator = () [] and -> must be members, and class-specific
    operators new, new[], delete and delete[] must be static members. If the situation
    arises where we don't need the object of the class to invoke a function, then make
    the function static. For all other functions:
    if a function requires the operators = () [] and -> for stream I/O,
    or if it needs type conversions on its leftmost argument, or if it can be implemented using the class' public interface alone, make it nonmember ( and friend if needed in the first two cases)
    if it needs to behave virtually,
    add a virtual member function to provide the virtual behaviour
    and implement in terms of that
    else
    make it a member.

提交回复
热议问题