C++ friend inheritance?

前端 未结 4 1937
野趣味
野趣味 2020-12-14 14:22

Does a subclass inherit, the main class\' friend associations (both the main class\' own and other classes friended with the main class)?

Or to put it differently, h

相关标签:
4条回答
  • 2020-12-14 15:03

    You can create (static) protected methods in the parent that will allow you to do things like that.

    class MyFreind
    {
    private:
        int m_member;
        friend class Father;
    };
    
    class Father
    {
    protected:
        static int& getMyFreindMember(MyFreind& io_freind) { return io_freind.m_member; }
    };
    
    class Son : public Father
    {
    public:
        void doSomething(MyFriend& io_freind)
        {
            int& friendMember = getMyFreindMember(io_freind);
            // ....
        } // ()
    };
    

    This however bypasses encapsulation so you probably should take a second look at your design.

    0 讨论(0)
  • 2020-12-14 15:03

    The answer is very simple: no, subclasses do not inherit friend associations. A friend can only access the private members of the class the association is declared in, not those of parents and/or children of that class. Although you might be access protected member of a superclass, but I'm not sure about that.

    0 讨论(0)
  • 2020-12-14 15:16

    Friendship is not inherited in C++.

    The standard says (ISO/IEC 14882:2003, section 11.4.8):

    Friendship is neither inherited nor transitive.

    0 讨论(0)
  • 2020-12-14 15:17

    friend only applies to the class you explicitly make it friend and no other class.

    http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4

    0 讨论(0)
提交回复
热议问题