0221作业
找到第一天mystring练习,实现以下功能 mystring str = "hello" mystring ptr = "world" str = str + ptr; str += ptr str[0] = 'H'
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
using namespace std;
class mystring{
private:
char* p;
int len;
public:
mystring(const char* s="")
{
len=strlen(s);
if(len!=0){
p=(char*)calloc(1,len+1);
strcpy(p,s);
}else{
p=NULL;
}
cout<<"构造函数"<<endl;
}
~mystring()
{
free(p);
}
void show()
{
cout<<p<<endl;
}
friend mystring operator+(const mystring& l,const mystring& r);
friend mystring& operator=(mystring& l,mystring& r);
friend mystring& operator+=(mystring& l,mystring& r);
friend char& operator[](mystring& l,int insert);
};
mystring operator+(mystring& l,mystring& r){
mystring temp;
temp.len=l.len+r.len;
temp.p=(char*)calloc(1,temp.len+1);
strcpy(temp.p,l.p);
strcat(temp.p,r.p);
return temp;
}
mystring& operator=(mystring& l,mystring& r){
free(l.p);
l.p=(char*)calloc(1,r.len+1);
l.len=r.len;
strcpy(l.p,r.p);
return l;
}
mystring& operator+=(mystring& l,mystring& r){
char *temp=l.p;
l.len=l.len+r.len;
l.p=(char*)calloc(1,l.len+1);
strcpy(l.p,temp);
strcat(l.p,r.p);
free(temp);
return l;
}
char& operator[](mystring& l,int insert){
return l.p[insert];
}
int main(int argc,const char** argv){
mystring str="hello";
mystring ptr="world";
str=str+ptr;
str+=ptr;
str[0]='H';
return 0;
}
封装消息队列 class Msg{ key_t key int id; int channel } 实现以下功能 Msg m("文件名") m[1].send("数据"),将数据发送到1号频道中 string str = m[1].read(int size) 从1号频道中读取消息,并且返回 编写程序测试
#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
using namespace std;
class Msg {
private:
key_t key;
int id;
vector<queue<string>> channels; // 每个频道的消息队列
public:
Msg(const string& filename) {
// 创建消息队列的键值
key = ftok(filename.c_str(), 'a');
if (key == -1) {
perror("ftok");
exit(1);
}
// 创建消息队列
id = msgget(key, 0666 | IPC_CREAT);
if (id == -1) {
perror("msgget");
exit(1);
}
// 初始化频道
channels.resize(10); // 假设最多支持10个频道
}
~Msg() {
// 删除消息队列
msgctl(id, IPC_RMID, nullptr);
}
// 下标运算符,返回特定频道
class Channel& operator[](int index) {
return channels[index];
}
class Channel {
private:
Msg& msg;
int channel_id;
public:
Channel(Msg& m, int id) : msg(m), channel_id(id) {}
void send(const string& data) {
// 将消息发送到指定频道
channels[channel_id].push(data);
}
string read(int size) {
// 从指定频道读取消息
if (channels[channel_id].empty()) {
return ""; // 如果队列为空,返回空字符串
}
string data = channels[channel_id].front();
channels[channel_id].pop();
return data.substr(0, size); // 返回指定大小的消息
}
};
// 返回特定频道的代理对象
Channel& getChannel(int index) {
return channels[index];
}
};
int main() {
Msg m("testfile");
// 发送消息到1号频道
m.getChannel(1).send("Hello, World!");
// 从1号频道读取消息
string str = m.getChannel(1).read(100);
cout << "Received: " << str << endl;
return 0;
}