Friend function is not visible in the class

后端 未结 4 993
臣服心动
臣服心动 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:45

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

    The above code works perfectly.(tried on DevC++) Also try not to define the function inside the class as it might not have a scope outside it i.e. in main(). In trying to call f() from main() you'll receive an error saying function doesn't exist. Therefore, define function outside classes using :: operator (if necessary) so that there is no problem accessing the function from anywhere. Access friend function defined in class

提交回复
热议问题