c – 从基类继承时,嵌套类会发生什么?

前端之家收集整理的这篇文章主要介绍了c – 从基类继承时,嵌套类会发生什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有这些课程:
class Base
{
    public:

        class Foo { ... };

        ...
};

那么另一个类派生自基地:

class Derived : public Base
{
    // no mention or redefinition of nested class "Foo" anywhere in "Derived"
};

这是否意味着我们现在有一个独特的Derived :: Foo,或者Derived :: Foo与Base :: Foo完全相同?

以下是这种情况的转折:如果有人抛出Derived :: Foo的实例呢?在这种情况下会被抓住吗?

catch ( const Base::Foo &ex )
{
    // would this also catch an instance of Derived::Foo?
}

解决方法

Base :: Foo和Derived :: Foo确实是相同的类型,类只是一个复合类型(从 draft C++ standard部分3.9.2),我们不会指望从基类继承的类型是不同的类型派生类.例如,如果Base包含:
typedef int newType1 ;

只要Derived没有重新声明newType1,那么我们期望Base :: newType1和Derived :: newType1是相同的类型,而嵌套类没有什么不同.如果我们参考标准草案9.2节班级成员第1段说(强调我的):

[…]Members of a class are data members,member functions (9.3),nested types,and
enumerators. Data members and member functions are static or non-static; see 9.4. Nested types are
classes (9.1,9.7) and enumerations (7.2) defined in the class,and arbitrary types declared as members by use of a typedef declaration (7.1.3)
.

这证实了直觉嵌套类只是类型(也是成员),为了完整性,上面引用的部分9.7是嵌套类部分,从第10节派生类第1段我们看到:

[…]Unless redeclared in the derived class,members of a base class are also considered to be members of the derived class.[…]

由于它们是相同的类型,捕获将正常工作.

猜你在找的C&C++相关文章