在下面的示例中(为篇幅道歉),我试图隔离在从另一个私有继承的类中使用嵌套类时遇到的一些意外行为。我经常看到这样的声明,即嵌套类与非嵌套类相比没有什么特别之处,但在这个例子中,我们可以看到嵌套类(至少根据 GCC 4.4)可以看到一个公共类型定义由关闭类私有继承的类。
我很欣赏 typdef 与成员数据不同,但我发现这种行为令人惊讶,我想许多其他人也会如此。所以我的问题是双重的:
- 这是标准行为吗?(一个体面的解释为什么会非常有帮助)
- 可以期望它在大多数现代编译器上工作(即,它的可移植性如何)?
#include <iostream>
class Base {
typedef int priv_t;
priv_t priv;
public:
typedef int pub_t;
pub_t pub;
Base() : priv(0), pub(1) {}
};
class PubDerived : public Base {
public:
// Not allowed since Base::priv is private
// void foo() {std::cout << priv << "\n";}
class Nested {
// Not allowed since Nested has no access to PubDerived member data
// void foo() {std::cout << pub << "\n";}
// Not allowed since typedef Base::priv_t is private
// void bar() {priv_t x=0; std::cout << x << "\n";}
};
};
class PrivDerived : private Base {
public:
// Allowed since Base::pub is public
void foo() {std::cout << pub << "\n";}
class Nested {
public:
// Works (gcc 4.4 - see below)
void fred() {pub_t x=0; std::cout << x << "\n";}
};
};
int main() {
// Not allowed since typedef Base::priv_t private
// std::cout << PubDerived::priv_t(0) << "\n";
// Allowed since typedef Base::pub_t is inaccessible
std::cout << PubDerived::pub_t(0) << "\n"; // Prints 0
// Not allowed since typedef Base::pub_t is inaccessible
//std::cout << PrivDerived::pub_t(0) << "\n";
// Works (gcc 4.4)
PrivDerived::Nested o;
o.fred(); // Prints 0
return 0;
}