如果将类A定义在类C的内部,那么类A就是一个内部类(嵌套类)
内部类的特点
1. 支持 Public, protected, private权限
2. 成员函数可以直接访问外部类对象的所有成员(反过来则不行)
3. 成员函数可以直接不带类名,对象名访问其外部类的static成员
4. 不会影响外部类的内存布局。(仅仅是限制了访问权限)
5. 可以在外部类内部声明,在外部类外面进行定义
1. 支持 Public, protected, private权限
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
int m_age;
public:
class Car
{
private:
int m_price;
};
};
int main(){
Person::Car car1; // 如果Car是private或protected属性,则Person::Car car1将会出错,因为Car 对象只能允许出现在类里面或子类中。
return 0;
}
2. 成员函数可以直接访问外部类对象的所有成员(反过来则不行)
class Person
{
private:
int m_age;
void test(){
Car car;
car.m_price = 10; //出错
}
public:
class Car
{
private:
int m_price;
void run() {
Person person;
person.m_age = 10; //正确
}
};
};
3. 成员函数可以直接不带类名,对象名访问其外部类的static成员
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
static int m_age;
int height;
static void test(){}
public:
class Car
{
private:
int m_price;
void run(){
// 可通过类直接使用静态成员和静态函数
Person::m_age = 20;
Person::test();
// 可直接访问外部类的静态成员和静态函数
m_age = 10;
test();
Person person;
person.height = 50;
}
};
};
5. 声明和实现分离
1) 可以在外部类内部声明,在外部类外面进行定义
class Point{
class Math{
void test();
};
};
void Point::Math::test(){}
2) 方法的声明和定义都放在外部类外面
class Point{
class Math;
};
// 方法的声明和定义都放在外部类外面
class Point::Math{
void test(){}
};
3) 方法的声明和定义都放在外部类外面,且声明和定义分开
class Point{
class Math;
};
//函数的声明
class Point::Math{
void test();
};
// 函数的定义
class Point::Math{
void test(){}
};