版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012581760/article/details/87708970
内部类
如果将类A定义在类C的内部,那么类A就是一个内部类(嵌套类).
内部类的特点
支持public,protected,private权限.
成员函数可以直接访问其外部类对象的所有成员(反过来则不行)
成员函数可以直接不带类名,对象名访问其外部类的static成员
不会影响外部类的内部布局
可以在外部类内部声明,在外部类外部进行定义
// Person
class Person {
int m_age;
void walk() {}
public:
static int ms_legs;
Person() {
cout << "Person()" << endl;
}
// Car
class Car {
int m_price;
public:
Car(){
cout << "Car()" << endl;
}
void run() {
Person person;
person.m_age = 10;
person.walk();
ms_legs = 10;
}
};
};
int main() {
Person person;
Person::Car car;
getchar();
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() {}
局部类
局部类:
在一个函数内部定义的类,称为局部类
局部类特点:
作用域仅限于所在的函数内部
其所有的成员必须定义在类内部,不允许定义static成员变量.
成员函数不能直接访问函数的局部变量(static 变量除外)
int g_age = 20;
void test() {
static int s_age = 30;
// 局部类
class Person {
public:
static void run() {
g_age = 30;
s_age = 40;
cout << "run() "<< endl;
}
};
Person person;
Person::run();
}
int main() {
getchar();
return 0;
}