class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : public ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// This class is capable of being instantiated
};
上面的没能密封类,但是下面的能用,为什么?
class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : public virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
这里发生了什么?虚拟继承在这里扮演什么角色?
最佳答案
对于正常的继承,派生类的构造函数只调用直接基类的构造函数。所以在第一个例子中,FailsToDerive
的构造函数调用 Sealed
的构造函数,它又调用 ClassSealer
的构造函数,这是允许的。
然而,虚拟 继承基类的构造函数由最派生类 的构造函数调用。所以在第二个例子中,FailsToDerive
的构造函数需要能够调用 ClassSealer
的构造函数,不允许这样做,因为它不是 ClassSealer
的友元.
关于c++ - C++ 中的密封类和虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33841954/