C++支持类的嵌套,其语法比较简单。代码是最好的说明。
1 #include2 using namespace std; 3 4 class Outter{ 5 public: 6 int a; 7 static int s; 8 //nested class and enclosing class are independent. 9 class Inner{ 10 public:11 int b;12 //nested class can access static members of enclosing class13 int foo(){ return b + s;}14 int bar();15 };16 };17 18 int Outter::s = 1;19 //define a nested class member outside of the class declaration.20 int Outter::Inner::bar(){21 return 0xdeadbeef;22 }23 24 int main(){25 Outter o;26 o.a = 0;27 //if nested class is specified as public, then everyone can use the nested class.28 //if nested class is specified as protected, then only the enclosing class,29 //friend of the enclosing class and derived class of the enclosing class can access the nested class.30 //if the nested class is specified as private, then only the enclosing class31 //and friend of the enclosing class can access the nested class.32 Outter::Inner i;33 i.b = 1;34 cout< <