嵌套类
在 C++ 中,嵌套类是指在一个类的内部定义的另一个类,又叫内部类。
外围类可以访问嵌套类的公有成员,但是嵌套类不能访问外围类的公有成员。
案例:
#include <iostream>
using namespace std;
class OutClass {
public:
class InClass { //嵌套类,又叫内部类
public:
void func(); //InClass的func
};
public:
InClass obj;
void func() { //OutClass的func
cout << "OutClass的func" << endl;
}
};
//OutClass作用域的InClass作用域的func函数,也就是InClass的func函数的定义
void OutClass::InClass::func() {
cout << "InClass的func" << endl;
}
void test01() {
OutClass outer;
outer.func(); //外围类的func
outer.obj.func(); //嵌套类的func
}
int main() {
test01();
return 0;
}
输出结果:
OutClass的func
InClass的func
实际的应用:
#include <iostream>
class Container {
private:
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
Node* head;
public:
Container() : head(nullptr) {}
void add(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
~Container() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
};
int main() {
Container container;
container.add(10);
return 0;
}
Node 类是 Container 类的嵌套类,用于实现链表节点。外部代码无法直接访问 Node 类,只能通过 Container 类提供的公共接口来操作链表,从而实现了类型封装。
局部类
类也可以定义在函数体内,这样的类被称为局部类。
type funcName(parameter list) {//函数
class 局部类名{//类体
};
}
具体跟上面类似,不过多赘述。
1464

被折叠的 条评论
为什么被折叠?



