(1)简介:
内部类其实就是一种在类声明里面定义的一种局部数据类型。(非常类似于struct Node声明的),这和java的还有存在区别的。
---- 内部类的声明有public和private之分
如果声明为public,那么外面也可以用它来定义变量,比如Outer::Inner var
如果声明为private,那么外面不能用来定义变量,那么Outer::Inner var将会导致编译错误。
(2)---- 内部类声明完之后就可以用来定义变量
这就和别的数据类型定义变量一样了,访问规则也一样。无他
---- 内部类和外部类的互相访问
不能访问, 完全依赖于成员变量的定义属性。
(3)代码实现(请看下面的注释,这里不做过多解释了)
#include <iostream> using namespace std; class A { public: class B1 { public: int a; private: int b; public: void foo(A &p) { cout << p.i1 << endl; // OK, because i1 is public in class A cout << p.i2 << endl; // Fail, because i2 is private in class A } }; private: class B2 { public: int a; private: int b; public: void foo(A &p) { cout << p.i1 << endl; // OK, because i1 is public in class A cout << p.i2 << endl; // Fail, because i2 is private in class A } }; public: B1 b11; B2 b12; int i1; private: B1 b21; B2 b22; int i2; public: void f(B1& p) { cout << p.a << endl; // OK, because a is public in class B1 cout << p.b << endl; // Fail, because b is private in class B1 } void f(B2& p) { cout << p.a << endl; // OK, because a is public in class B2 cout << p.b << endl; // Fail, because b is private in class B2 } }; int main(int argc, char *argv[]) { A a ; A::B1 ab1; // OK, because B1 is declared as public inner class. A::B2 ab2; // Fail, because B2 is declared as private inner class return 0; }
时间: 2024-10-07 15:21:05