【C++细节】友元函数

概念

A friend function is a function that is not a member of a class but has access to the class’s private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class’s scope, and they are not called using the member-selection operators (. and –>) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

来自 http://blog.****.net/yiruirui0507/article/details/5983333

注意最后一句:友元函数不受访问控制关键字(public等)影响


类内定义友元函数

  1. 参数中必须含有该类的参数,否则会找不到函数:
    【C++细节】友元函数

    参见C++标准7.3.1.2节第三段:
    The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). If a friend function is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2).

    C++标准3.4.2节(Argument-dependent name lookup)第四段:
    Any namespace-scope friend functions or friend function templates declared in associated classes are visible within their respective namespaces even if they are not visible during an ordinary lookup (11.3).

    也就是说,除非友元函数带了class A的参数,可以通过Argument-dependent name lookup(ADL)被找到,否则必须在作用域里有声明才能在作用域中可见。

    来自 https://zhidao.baidu.com/question/2137574232233832708.html

  2. 该函数的作用域为文件作用域,不论该类在什么命名空间内:
    【C++细节】友元函数

  3. 同时是内联函数:

    Friend functions can be defined inside class declarations. These functions are inline functions, and like member inline functions they behave as though they were defined immediately after all class members have been seen but before the class scope is closed (the end of the class declaration).

    Friend functions defined inside class declarations are not considered in the scope of the enclosing class; they are in file scope.

    来自 https://msdn.microsoft.com/en-us/library/465sdshe.aspx


类外定义友元函数:

  1. 无论函数定义在什么命名空间中皆可:
    【C++细节】友元函数

  2. 不能同时在类内定义,类似于重定义