c++ 友元关系与继承

友元关系不能继承。基类的友元对派生类的成员没有特殊访问权限。

如果基类被授予友元关系,则只有基类具有特殊访问权限,该基类的派生类不能访问授予友元关系的类。

class Base
{
    friend class frnd;
protected:
    int i;
}

// Frnd has no access to members in D1
class D1 : public Base
{
protected:
    int j;
};

class Frnd
{
public:
    int mem(Base b) { return b.i; } // ok: Frnd is friend to Base
    int mem(D1 d) { return d.i; } // error: friendship doesn’t inherit
};

// D2 has no access to members in Base
class D2 : public Frnd
{
public:
    int mem(Base b) { return b.i; } // error: friendship doesn’t inherit
};

 

 

posted on 2013-02-25 20:48  zhuyf87  阅读(3096)  评论(0编辑  收藏  举报

导航