C++ 内部类(嵌套类)
一、什么是内部类
内部类 / 嵌套类 :在一个类的里面再定义另一个类。
cpp
class Outer // 外部类
{
class Inner // 内部类
{
};
};
关键点:
-
内部类是外部类的成员
-
内部类受
public / private / protected访问权限控制 -
内部类不默认拥有外部类对象,不能直接随便访问外部类成员
二、基础语法 + 最简示例代码
cpp
#include <iostream>
using namespace std;
// 外部类
class Outer
{
// 公有内部类:外部可以访问
public:
class Inner
{
public:
void hello()
{
cout << "我是内部类的成员函数" << endl;
}
};
};
int main()
{
// 外部类::内部类 定义对象
Outer::Inner in;
in.hello();
return 0;
}
输出:
cpp
我是内部类的成员函数
写法记住:外部类名::内部类名
三、内部类设为 private(外部无法访问)
cpp
#include <iostream>
using namespace std;
class Outer
{
// 私有内部类:只能在外部类内部使用
private:
class Inner
{
public:
void test()
{
cout << "私有内部类" << endl;
}
};
public:
// 外部类内部可以创建内部类对象
void createInner()
{
Inner in;
in.test();
}
};
int main()
{
Outer out;
out.createInner();
// 错误!Inner 是 private,外部不能访问
// Outer::Inner in;
return 0;
}
输出:
cpp
私有内部类
总结:
-
private内部类:仅外部类内部可用,外界看不见 -
public内部类:全局可用 ,通过Outer::Inner创建
四、内部类 和 外部类 互相访问规则(重点)
核心规则
-
内部类可以访问外部类的静态成员
-
内部类不能直接访问外部类普通成员(没有外部类对象)
-
要访问外部类普通成员,必须传外部类对象进去
-
外部类可以直接使用内部类
代码演示:访问静态成员
cpp
#include <iostream>
using namespace std;
class Outer
{
public:
static int num; // 外部类静态成员
int age; // 外部类普通成员
class Inner
{
public:
void show()
{
// 可以直接访问外部类静态成员
cout << "外部类静态num = " << Outer::num << endl;
// 错误:不能直接访问普通成员
// cout << age << endl;
}
};
};
// 静态成员初始化
int Outer::num = 100;
int main()
{
Outer::Inner in;
in.show();
return 0;
}
代码演示:内部类访问外部类普通成员(传对象)
cpp
#include <iostream>
using namespace std;
class Outer
{
public:
int age = 20;
class Inner
{
public:
// 传入外部类对象
void getOuterAge(const Outer& out)
{
cout << "外部类age = " << out.age << endl;
}
};
};
int main()
{
Outer out;
Outer::Inner in;
in.getOuterAge(out);
return 0;
}
输出:
外部类age = 20
五、外部类使用内部类
cpp
#include <iostream>
using namespace std;
class Outer
{
public:
class Inner
{
public:
void hello()
{
cout << "内部类hello" << endl;
}
};
// 外部类函数中直接用内部类
void useInner()
{
Inner in;
in.hello();
}
};
int main()
{
Outer out;
out.useInner();
return 0;
}
六、内部类也可以有构造函数、成员函数
cpp
#include <iostream>
#include <string>
using namespace std;
class Outer
{
public:
class Inner
{
private:
string msg;
public:
// 内部类构造函数
Inner(string s) : msg(s) {}
void show()
{
cout << msg << endl;
}
};
};
int main()
{
Outer::Inner in("内部类带参构造");
in.show();
return 0;
}
七、内部类 核心考点总结(必背)
-
内部类 = 定义在类里面的类;
-
访问方式:
外部类::内部类; -
内部类也有
public/private/protected权限; -
private 内部类只能外部类内部使用,外部无法创建;
-
内部类可直接访问外部类静态成员;
-
内部类访问外部类普通成员,必须传入外部类对象;
-
外部类可以直接随便使用内部类;
-
内部类是独立的类,不隐含 this 指向外部类。