c++ - 从基类继承时,嵌套类会发生什么情况?

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

假设我有这些类(class):

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?
}

最佳答案

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

关于c++ - 从基类继承时,嵌套类会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529241/

相关文章:

c++ - 用基本类型标记的 Boost Graph 边缘的简单点输出

c++ - 旋转后字典序最小的字符串

c#在方法的参数中继承一个带有派生类的接口(interface)

php - 具有继承和覆盖的分层 ACl

python - django-tables2 : Table subclassing and Meta inner class attributes

python - python 中的 perror 等效函数

c++ - 自定义迭代器: how to correctly handle distance calculation and equality comparison between a and b if the behavior of those differe

c++ - 我写了一个简单的 vector 程序,其中我得到了以下输出。你能帮我理解它的输出吗?

javascript - 如何捕获输入元素的内容并测试它是否是字母 a-z A-Z 之间的字符,并且两个单词之间有空格

Powershell tr​​y-catch ...其他?