嵌套类、局部类

嵌套类

在 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 局部类名{//类体

    };
}

具体跟上面类似,不过多赘述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值