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

1. operator运算符重载

创建mystring实现以下功能

mystring str = "hello"

mystring ptr = "world"

str = str + ptr;

str += ptr

str[0] = '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("文件名")

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

string str = m[1].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.init[1](10):手动初始化信号灯集中的第1个信号量,初始化成 10

s[1] + 1 让信号灯集中的第1个信号量的值 +1

s[1] - 1 让信号灯集中的第1个信号量的值 -1

编写程序测试

相关推荐
珹洺2 分钟前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
coding随想3 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
爱吃烤鸡翅的酸菜鱼22 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发7 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++