Is there any difference if we define friend function inside or outside of class

前端 未结 6 1303
借酒劲吻你
借酒劲吻你 2020-12-10 16:09

What is the difference between defining friend function inside the class or declaring inside and define outside of the class. Also why it is possible to place definition ins

6条回答
  •  温柔的废话
    2020-12-10 16:14

    There are subtle implications of the following regarding member access.

    C++11 §11.4/5

    A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).

    Still there as of C++17 §14.3/7

    Such a function is implicitly an inline function (10.1.6). A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (6.4.1).

    Consider the condenced example from cppreference [Friend function definition], where f1 finds class static member and f2 finds global variable.

    int i = 3;
    struct X {
        friend void f1(int x) {
            i = x; // finds and modifies X::i
        }
        friend inline void f2(int);
        static const int i = 2;
    };
    
    inline void f2(int x) {
        i = x; // finds and modifies ::i
    }
    

    Of course this can't affect design desicions for the friend function. The main consideration between choices is a difference in name look up as already mentioned in the other answer. Don't forget the inline for f2 to match those of f1 implied by default.

提交回复
热议问题