Why the object of the sub-class can’t
be considered as an object of
super-class, when the inheritance is
protected or private?
www.un.org/Depts/DGACM/index_spanish.htm 这当然可被视为超级阶级的物体。 然而,这种考虑受到限制(由公共/保护/私人继承人进行),但仅限于 /strong>(私人继承)或 次类别(受保护的继承)。
不允许所有外部物体视同这种类别,与它们不允许接触受保护或私人方法或变量。 如果适当表述,这种类比就相当合适。
因此,阶级本身、其子阶级(和朋友)可以将此视为一种亲子关系,但外部世界不允许这样做。
下面的法典在行动中表明了这一点:
class Base {
public: virtual ~Base() {}
};
class PublicDerived: public Base
{ };
class ProtectedDerived: protected Base {
void test() {
Base* base2 = this; // OK
}
};
class ProtectedSubClass: public ProtectedDerived {
void test() {
Base* base2 = this; // OK
}
};
class PrivateDerived: private Base {
void test() {
Base* base2 = this; // OK
}
};
class PrivateSubClass: public PrivateDerived {
void test() {
Base* base2 = this; // Error (line 28)
}
};
int main()
{
PublicDerived publicD;
ProtectedDerived protectedD;
PrivateDerived privateD;
Base* base1 = &publicD;
Base* base2 = &protectedD; // Error (line 39)
Base* base3 = &privateD; // Error (line 40)
}
请注意,这并不涉及xxxSubClass-classes如何从其超级类别中得出。 www.un.org/Depts/DGACM/index_french.htm
编辑们适当抱怨:
inherit.cpp(28) : error C2247: Base not accessible because PrivateDerived uses private to inherit from Base
inherit.cpp(1) : see declaration of Base
inherit.cpp(20) : see declaration of PrivateDerived
inherit.cpp(1) : see declaration of Base
inherit.cpp(29) : error C2243: type cast : conversion from PrivateSubClass *const to Base * exists, but is inaccessible
inherit.cpp(39) : error C2243: type cast : conversion from ProtectedDerived * to Base * exists, but is inaccessible
inherit.cpp(40) : error C2243: type cast : conversion from PrivateDerived * to Base * exists, but is inaccessible