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

Sté*_*ane 11 c++ inheritance try-catch nested-class

说我有这些课程:

class Base
{
    public:

        class Foo { ... };

        ...
};
Run Code Online (Sandbox Code Playgroud)

然后另一个类派生自基数:

class Derived : public Base
{
    // no mention or redefinition of nested class "Foo" anywhere in "Derived"
};
Run Code Online (Sandbox Code Playgroud)

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

以下是这种情况的一个转折:如果有人抛出一个实例Derived::Foo怎么办?它会在这种情况下被捕获:

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

Dan*_*rey 10

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& ) {}
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这也意味着将其抛出一个名称并将其捕获到其他作品中.

实例