Friend function is not visible in the class

后端 未结 4 997
臣服心动
臣服心动 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条回答
  •  萌比男神i
    2020-12-16 18:27

    This quote from the C++ Standard

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

    means the following

    9 Name lookup for a name used in the definition of a friend function (11.3) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions.

    That is any name used in the function is searched starting from the class scope.

    However the function itself is not visible in the namespace until it will be declared outside the class.

    So in your case it is enough to declare the function before the class definition

    void f() {}
    
    struct M {
        friend void f();
        M() {
            f(); 
        }
    };
    
    int main() {
        M m;
    }
    

    Or

    void f();
    
    struct M {
        friend void f() {}
        M() {
            f(); 
        }
    };
    
    int main() {
        M m;
    }
    

提交回复
热议问题