在子类函数中访问超类友元的受保护数据成员



有三个类A,B,C;A类是B,B,B具有受保护的数据成员。C类从A类公开继承。我可以通过在C的函数中初始化B对象来访问B的受保护数据成员吗?

如果不是,我将如何访问C函数中的B值?

您无法直接访问C中的B的受保护成员,但是您可以在A中获取/设置B中的受保护成员的A中引入一个受保护的方法;由于C是从A中派生的,您可以在A中访问受保护的GET/SET方法,请参见下面的示例。不过,最好考虑整体设计。

class A
{
protected:
    int getValueOfB(B& b) { return b.protectedValue; }
    void setValueInB(B& b, int value) { b.protectedValue = value; }
};
class C
{
    void doSomething()
    {
       B b;
       setValueInB(b, 1);
    }
}

friend未继承。
friendfriend不是friend

作为替代方案,Passkey Idiom在您的情况下可能会有所帮助:

class B;
class A
{
public:
    struct Key{
        friend class B; // no longer in class A.
    private:
        Key() = default;
        Key(const Key&) = default;
    };
    // ...
};
class C : public A
{
private:
    void secret(Key /*, ...*/) { /*..*/ }
};
class B
{
public:
    void foo(C& c) {
         c.secret(A::Key{}); // Access C private thanks to "private" key from A.
    }
};

最新更新