每个类控制对自己的成员的友元关系:

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
};
如果派生类想要将自己成员的访问权授予其基类的友元,派生类必须显式地这样做:基类的友元对从该基类派生的类型没有特殊访问权限。同样,如果基类和派生类都需要访问另一个类,那个类必须特地将访问权限授予基类的和每一个派生类。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
};
2、继承与静态成员
如果基类定义 static 成员(第 12.6 节),则整个继承层次中只有一个这样的成员。无论从基类派生出多少个派生类,每个 static 成员只有一个实例。static 成员遵循常规访问控制:如果成员在基类中为 private,则派生类不能访问它。假定可以访问成员,则既可以通过基类访问 static 成员,也可以通过派生类访问 static 成员。一般而言,既可以使用作用域操作符也可以使用点或箭头成员访问操作符。

[color=#0000FF]struct Base {
static void statmem(); // public by default
};
struct Derived : Base {
void f(const Derived&);
};
void Derived::f(const Derived &derived_obj)
{
Base::statmem(); // ok: Base defines statmem
Derived::statmem(); // ok: Derived in herits statmem
// ok: derived objects can be used to access static from base
derived_obj.statmem(); // accessed through Derived object
statmem(); // accessed through this class
}
[/color] static void statmem(); // public by default
};
struct Derived : Base {
void f(const Derived&);
};
void Derived::f(const Derived &derived_obj)
{
Base::statmem(); // ok: Base defines statmem
Derived::statmem(); // ok: Derived in herits statmem
// ok: derived objects can be used to access static from base
derived_obj.statmem(); // accessed through Derived object
statmem(); // accessed through this class
}