【问题标题】:When inheriting from a base class, what happens with nested classes?从基类继承时,嵌套类会发生什么?
【发布时间】:2013-10-31 23:52:17
【问题描述】:

假设我有这些课程:

class Base
{
    public:

        class Foo { ... };

        ...
};

然后从基类派生另一个类:

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

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

这里有一个转折点:如果有人抛出Derived::Foo 的实例怎么办?在这种情况下会不会被抓住:

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

【问题讨论】:

    标签: c++ inheritance try-catch nested-class


    【解决方案1】:

    Derived::Foo 只是访问Base::Foo,因此这只是引用同一类型的两种方式。您可以通过std::is_same 轻松查看:

    #include <type_traits>
    
    struct Base
    {
        class Foo {};
    };
    
    struct Derived : Base {};
    
    static_assert( std::is_same< Base::Foo, Derived::Foo >::value, "Oops" );
    
    int main()
    {
        try {
            throw Derived::Foo();
        }
        catch( const Base::Foo& ) {}
    }
    

    如您所见,这也意味着以一个名字抛出它并由其他作品捕捉它。

    Live example

    【讨论】:

      【解决方案2】:

      Base::FooDerived::Foo 确实是相同的类型,一个类只是一个复合类型(来自draft C++ standard 部分3.9.2),我们不会期望从基类继承的类型派生类中的不同类型。例如,如果 Base 包含:

      typedef int newType1 ;
      

      只要Derived 没有重新声明newType1,那么我们预计Base::newType1Derived::newType1 是相同的类型 并且嵌套类 是没有什么不同。如果我们参考草案标准部分9.2Class members 段落 1 说(emphasis mine):

      [...]类的成员是数据成员、成员函数 (9.3)、嵌套类型和 枚举器。数据成员和成员函数是静态的或非静态的;见 9.4。 嵌套类型是 类中定义的类(9.1、9.7)和枚举(7.2),以及使用typedef声明(7.1.3)声明为成员的任意类型

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

      [...]除非在派生类中重新声明,否则基类的成员也被视为派生类的成员。[...]

      由于它们是同一类型,catch 可以正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多