基于char*设计一个字符串类MyString
发布网友
发布时间:2023-07-20 16:15
我来回答
共1个回答
热心网友
时间:2024-12-05 06:39
//MStr.h
#pragma once
#include<iostream>
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;
intlen;
};
//MStr.cpp
#include "MStr.h"
#include<string.h>
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<<MS.str;
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)
{
deletestr;
}
//main.cpp
#include<iostream>
#include"MStr.h"
using namespace std;
int main()
{
MStr str1("Hello"),str2("World");
cout<<str1<<endl;
cout<<MStr(str2)<<endl;
cout<<str1+str2<<endl;
while(1);
}
//最终结果