cpp_inner_classes - ShenYj/ShenYj.github.io GitHub Wiki
-
如果将类A定义在类C的内部,那么类A就是一个内部类(嵌套类)
-
内部类的特点
- 支持public、protected、private权限
- 成员函数可以直接访问其外部类对象的所有成员(反过来则不行), 包括私有成员
- 成员函数可以直接不带类名、对象名访问其外部类的static成员
- 不会影响外部类的内存布局
- 可以在外部类内部声明,在外部类外面进行定义
-
示例
class Point { static void test1() { cout << "Point::test1()" << endl; } static int ms_test2; int m_x; int m_y; public: class Math { public: void test3() { cout << "Point::Math::test3()" << endl; test1(); ms_test2 = 10; Point point; point.m_x = 10; point.m_y = 20; } }; }; int main() { /// 现在的访问权限是 public ,外面能够访问, 如果设置为 protected或private 就无法使用了 Point::Math math1; return 0; }
-
声明和实现分离
class Point {
class Math {
/// 声明
void test();
}
}
/// 实现
void Point::Math::test() {
}
class Point {
class Math;
}
class Point::Math {
void test() {
}
}
class Point {
class Math;
}
class Point::Math {
/// 声明
void test();
}
/// 实现
void Point::Math::test() {
}