Why would a struct need a friend function?

后端 未结 3 1343
刺人心
刺人心 2020-12-21 19:01

I\'m trying to build a program whose source I downloaded from the internet. When I try to compile it, I get the error message

friend declaration specifying          


        
3条回答
  •  失恋的感觉
    2020-12-21 19:36

    But more basically, I don't understand why a struct needs a friend function, since its members are public anyway.

    This is a misunderstanding. There are no structs and classes in C++, but C++ only has classes that can be declared with one of the keywords struct or class. The only difference is the default access, ie the following two are identical (apart from the order of their members, which matters if you take their address):

    struct foo : private bar {
        int x;
    private:
        int y;
    };
    

    And the same with class:

    class foo : bar {    
        int y;
    public:    
        int x;
    };
    

    Using class or struct to declare a class is purely a matter of convention. Hence, your question translates to "Why would a class need a friend function?" and the answer is: To allow the friend to access private fields.

    The question you linked is about defining the friend function inline vs just declaring it, ie

    struct foo { 
        friend void foofriend() { /*put implementation here*/ }
    };
    

    vs

    struct foo {
        friend void foofriend();
    };
    
    void foofriend() { /*put implementation here*/ }
    

    This is indeed related to ADL (tbh I also could not explain it) and is kind of orthogonal to the question what friends are good for.

提交回复
热议问题