呵呵,这里的每个人都说“不”。我说“是的,这确实有道理”。
class VirtualBase {
public:
virtual void vmethod() = 0;
// If "global" is an instance of Concrete, then you can still access
// VirtualBase's public members, even though they're private members for Concrete
static VirtualBase *global;
};
// This can also access all of VirtualBase's public members,
// even if an instance of Concrete is passed in,
void someComplicatedFunction(VirtualBase &obj, ...);
class Concrete : private VirtualBase {
private:
virtual void vmethod();
public:
void cmethod() {
// This assignment can only be done by Concrete or friends of Concrete
VirtualBase::global = this;
// This can also only be done by Concrete and friends
someComplicatedFunction(*this);
}
};
进行继承private
并不意味着您不能VirtualBase
从类外部访问 的成员,它仅意味着您不能通过对 . 的引用访问这些成员Concrete
。但是,它的朋友可以投射toConcrete
的实例,然后任何人都可以访问公共成员。简单地,Concrete
VirtualBase
Concrete *obj = new Concrete;
obj->vmethod(); // error, vmethod is private
VirtualBase *obj = VirtualBase::global;
obj->vmethod(); // OK, even if "obj" is really an instance of Concrete