加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:45:59 所属栏目:百科 来源:网络整理
导读:说我有这些课程: class Base{ public: class Foo { ... }; ...}; 那么另一个类派生自基地: class Derived : public Base{ // no mention or redefinition of nested class "Foo" anywhere in "Derived"}; 这是否意味着我们现在有一个独特的Derived :: Foo,
说我有这些课程:
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.[…]

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读