基于char*设计一个字符串类MyString

2025-06-28 21:50:38
推荐回答(1个)
回答1:

//MStr.h
#pragma once
#include
using namespace std;
class MStr
{
public:
MStr(void);
~MStr(void);//析构函数
MStr(char *);
MStr(const MStr&);//复制构造函数
const MStr operator +(const MStr &);//重载加法
friend ostream & operator <<(ostream &, const MStr &);//重载输出流
friend istream & operator >>(istream &, MStr &);//重载输入流
private:
char * str;
int len;
};
//MStr.cpp
#include "MStr.h"
#include
MStr::MStr(void)
{
str = new char;
str[0] = '\0';
len = 0;
}
MStr::MStr(char *s)
{
int size = strlen(s);
str = new char[size+1];
str[size] = '\0';
strcpy(str,s);
len = size;
}
MStr::MStr(const MStr &s)
{
len = s.len;
str = new char[len+1];
str[len] = '\0';
strcpy(str,s.str);
}
istream & operator >>(istream & in, MStr & MS)
{
in>>MS.str;
MS.len = strlen(MS.str);
return in;
}
ostream & operator <<(ostream & out, const MStr & MS)
{
out<return out;
}
const MStr MStr::operator+(const MStr & MS)
{
int newlen = len+MS.len;
char * newstr = new char[newlen+1];
newstr[newlen] = '\0';
strcpy(newstr,str);
strcpy(newstr+len,MS.str);
return MStr(newstr);
}
MStr::~MStr(void)
{
delete str;
}
//main.cpp
#include
#include"MStr.h"
using namespace std;
int main()
{
MStr str1("Hello"),str2("World");
cout<cout<cout<while(1);
}
//最终结果