C++ friend inheritance?

时光毁灭记忆、已成空白 提交于 2019-11-28 22:33:23

Friendship is not inherited in C++.

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

Friendship is neither inherited nor transitive.

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!