朋友继承自类的所有类

时间:2017-06-26 20:10:24

标签: c++ inheritance friend

这更像是一种求知欲而非实际问题。我想知道在C ++中是否有办法执行以下操作:让A成为一个类。我希望与B继承的所有类建立一个A类的朋友。

在你说之前:我显然知道友谊不是继承的。我想做的是为每个班级template friendB朋友发送C声明(可能使用SFINAE),以便C继承自A }}

这样的事情是否可能?我试着从最简单的案例开始:你能和其他所有班级成为一个班级朋友吗?显然我知道这没有任何意义,人们可以把事情公之于众,但也许从这个起点可以完善事情,只选择那些继承自A的类。

1 个答案:

答案 0 :(得分:1)

解决方法是使用继承的“密钥”访问权。

// Class to give access to some A members
class KeyA
{
private:
    friend class B; // Give access to base class to create the key
    KeyA() = default;
};


class A
{
public: // public, but requires a key to be able to call the method
    static void Foo(KeyA /*, Args... */) {}
    static void Bar(KeyA /*, Args... */) {}
};


class B
{
protected:
    static KeyA GetKey() { return KeyA{}; } // Provide the key to its whole inheritance
};

class D : public B
{
public:
    void Foo() { A::Foo(GetKey()); } // Use A member with the key.
};
相关问题