c – 朋友从类中继承的所有类

这更像是一种求知欲而非实际问题.我想知道在C中是否有办法做以下事情:让A成为一个班级.我想和B继承的所有类成为B级朋友.

在你说之前:我显然知道友谊不是继承的.我想做的是做一个模板友好声明,可能使用SFINAE,与每个C类的朋友B,以便C继承自A.

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

最佳答案 解决方法是使用继承的“密钥”访问.

// 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.
};
点赞