假设我有这些类(class):
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?
}
最佳答案
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& ) {}
}
如您所见,这也意味着用一个名字抛出它并用其他作品捕捉它。
关于c++ - 从基类继承时,嵌套类会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529241/