C++朋友继承?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7371087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:50:13  来源:igfitidea点击:

C++ friend inheritance?

c++subclassfriend

提问by SSight3

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, how does inheritance apply to the friend keyword?

或者换一种说法,继承如何应用于朋友关键字?

To expand: And if not, is there any way to inherit friendship?

扩展:如果没有,有没有什么方法可以继承友谊?

I have followed Jon's suggestion to post up the design problem:
C++ class design questions

我已经按照 Jon 的建议发布了设计问题:
C++ class design questions

回答by Jon

Friendship is not inherited in C++.

C++ 中没有继承友谊。

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

该标准说(ISO/IEC 14882:2003,第 11.4.8 节):

Friendship is neither inherited nor transitive.

友谊既不是继承的,也不是传递的。

回答by selalerer

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.

然而,这绕过了封装,因此您可能应该重新审视您的设计。

回答by balki

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

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

回答by Aardvark Soup

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.

答案很简单:不,子类不继承友元关联。朋友只能访问声明关联的类的私有成员,而不能访问该类的父级和/或子级的私有成员。尽管您可能是超类的受保护成员,但我不确定这一点。