2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】

1. operator运算符重载

创建mystring实现以下功能

mystring str = "hello"

mystring ptr = "world"

str = str + ptr;

str += ptr

str0 = 'H'

cpp 复制代码
#include <iostream>

using namespace std;

class mystring{

private:
	string str;
public:
	
	mystring(const string &str):str(str)
	{

	}

	mystring  operator+(const mystring& l)
	{
		return mystring(str+l.str);
	}

	mystring &operator+=(const mystring& l)
	{
		str+=l.str;
		return *this;
	}

	void show()
	{
		cout<<str<<endl;
	}
};

int main()
{
	mystring str("hello");
	mystring ptr("world");

	str=str+ptr;
	str.show();
	str+=ptr;
	str.show();


return 0;
}

2.封装消息队列

2.封装消息队列

class Msg{

key_t key

int id;

int channel

}

实现以下功能

Msg m("文件名")

m1.send("数据"),将数据发送到1号频道中

string str = m1.read(int size) 从1号频道中读取消息,并且返回

编写程序测试

cpp 复制代码
#include <iostream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include<cstring>

using namespace std;

class Msg{

	private:
		key_t key;
		int id;

		struct Msgbuf{
			long channel;
			char buf[128];
		};

	public:
		class Channel {

			private:

				int id;
				long channel;

			public:
				Channel(int id,long ch):id(id),channel(ch){}

				//发送数据
				void send (const string &data)
				{
					Msgbuf msg;
					msg.channel=channel;
					strncpy(msg.buf,data.c_str(),127);
					msgsnd(id,&msg,strlen(msg.buf),0);
				}

				//读取数据
				string read(int size)
				{
					Msgbuf msg;
					memset(&msg,0,sizeof(msg));
					msgrcv(id,&msg,size,channel,IPC_NOWAIT);
					return string(msg.buf);

				}


		};

		//构造函数
		Msg(const string &filename)
		{
			key=ftok("./ipc",2);
			id=msgget(key,IPC_CREAT|0666);

		}

		//重载
		Channel operator[](int ch)
		{
			return Channel(id,ch);
		}

};

int main()
{
	Msg m("./ipc");;

	m[1].send("hello");
	string str =m[1].read(128);

	cout<<str<<endl;

	return 0;
}

3. 封装信号灯集

封装信号灯集

class Sem{

key_t key

int id;

int index

}

实现以下功能

Sem s(参数x,参数y):创建信号灯集,信号灯集中存在 x 个信号量,并且将所有信号量初始化为 y

s.init1(10):手动初始化信号灯集中的第1个信号量,初始化成 10

s1 + 1 让信号灯集中的第1个信号量的值 +1

s1 - 1 让信号灯集中的第1个信号量的值 -1

编写程序测试

相关推荐
W是笔名6 分钟前
python___容器类型的数据___序列
开发语言·python
☆cwlulu7 分钟前
try-throw-catch异常捕获流程
开发语言·c++
漂亮的摩托13 分钟前
深感一无所长,准备试着从零开始写个富文本编辑器
开发语言·php
要开心吖ZSH20 分钟前
Java事务与MySQL事务的关系及MVCC通俗解析
java·开发语言·mysql·mvcc
王老师青少年编程30 分钟前
2026年6月GESP真题及题解(C++五级):排排坐
c++·题解·真题·gesp·五级·2026年6月·排排坐
寻道码路37 分钟前
LangChain4j Java AI 应用开发实战(二十六):多模型集成策略 —— OpenAI、DeepSeek、阿里百炼混合使用
java·开发语言·人工智能·ai
面朝大海,春不暖,花不开42 分钟前
BPF与eBPF简介:核心概念与观测工具概览
开发语言·php·ebpf·bpf·性能观测
ch.ju43 分钟前
Java Programming Chapter 4——Static code block
java·开发语言
弹简特1 小时前
【Java项目-企悦抽】04-项目演示+项目源码+AI赋能整理接口文档
java·开发语言
郝学胜-神的一滴1 小时前
Qt 高级编程 034:深耕QWidget底层内核—彻底吃透无边框窗口设计核心原理
开发语言·c++·qt·程序人生·软件开发·用户界面