假设这个结构
struct InterfaceForFoo
{
virtual void GetItDone() = 0;
};
class APoliticallyCorrectImplementationOfFooRelatedThings : private InterfaceForFoo
{
public:
void GetItDone() { /*do the thing already*/ };
};
现在,我想知道以这种方式从接口(interface)私有(private)继承是否有任何有用的场景。
最佳答案
哈,这里的每个人都说“不”。我说“是的,它确实有意义。”
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
的引用。但是,Concrete
及其 friend 可以将 Concrete
的实例转换为 VirtualBase
,然后任何人都可以访问公共(public)成员。简单地说,
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
关于c++ - 从抽象(纯虚拟)类私有(private)继承是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6642777/