Friend function is not visible in the class

后端 未结 4 1007
臣服心动
臣服心动 2020-12-16 17:43

I have the following code:

struct M {
    friend void f() {}
    M() {
        f(); // error: \'f\' was not declared in this scope
    }
};

int main() {
            


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 18:39

    The friend declaration states that a function called f in the surrounding namespace is a friend of the class; but it does not introduce the name f into the namespace. It's not available (except by argument-dependent lookup) until it's been declared in the namespace.

    The relevant rule is C++11 7.3.1.2/3:

    If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope.

提交回复
热议问题