保护/私人继承铸造 [英] Protected/Private Inheritance Casting
问题描述
当我去继承和上/下投射时,我偶然遇到了这个问题。为什么不允许这样做(代码被注释为显示不允许的部分)?
I came across this issue accidentally when I was going over inheritance and up/down casting. Why is this not allowed (code is commented to show sections that are not allowed)? Now I can guess as to why it is not allowed but a factual answer would be great.
至于允许的代码,我可以猜测为什么不允许这样做知道这是因为(Base *)是一个C风格的转换,它本质上是C ++中的一个 reinterpret_cast ,这反过来意味着在这种情况下它会导致未定义的行为。如果我错了,请更正我。
As for the code that is allowed, I know it is because (Base*) is a C-style cast which is essentially a reinterpret_cast in C++ which in turn means that in this case it will result in undefined behavior. Please correct me if I am wrong.
class Base
{
};
class Derived : public Base
{
};
class DerivedProt : protected Base
{
};
class DerivedPriv : private Base
{
};
int main()
{
Base* a = new Derived();
Base* b = new DerivedProt(); // Not allowed
Base* c = new DerivedPriv(); // Not allowed
Base* d = (Base*) new DerivedProt(); // Allowed but undefined behavior...?
Base* e = (Base*) new DerivedPriv(); // Allowed but undefined behavior...?
}
推荐答案
听起来你是正确的。
需要记住的一点是,传统的OO原则,如LSP只描述公共继承。非公共继承属于继承和组合之间,基本子对象是非公共的,像组合,但你也可以利用依赖于继承的功能,如虚函数。
One thing to remember is that traditional OO principles such as the LSP only describe public inheritance. Non-public inheritance falls in-between inheritance and composition, the base subobject is non-public like composition, but you can also take advantage of features which rely on inheritance, such as virtual functions.
但是,就像一个组成的子对象,只有类(或其后代,在受保护的继承的情况下),可以获得子对象的地址。
Just like a composed subobject, however, only the class (or its descendants, in case of protected inheritance), can get the address of the subobject.
这篇关于保护/私人继承铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!