#include<iostream.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
char *m_strcpy(char* strDest, const char *strSrc)// strlen(strcpy(s1,s2))
{
//const char *strSrc---> const在*左边 修饰指向内容
char * pDest=strDest;
const char * pSrc=strSrc;
while(*pSrc!='\0')
{
*pDest++=*pSrc++;
}
*pDest='\0';
return strDest;
}
int m_strlen(const char* strDest)
{
int cout=0;
const char *pDest=strDest;
while(*pDest!='\0')
{
cout++;
pDest++;
}
return cout;
}
int m_strcmp(char* strDest, const char *strSrc)
{
char* pDest=strDest;
const char* pSrc=strSrc;
if(pDest==NULL&&pSrc==NULL) return 0;
if(pDest==NULL&&pSrc!=NULL) return -1;
if(pDest!=NULL&&pSrc==NULL) return 1;
int k=0;
while((k=(*pDest-*pSrc))==0&&pDest++&&pSrc++)
return k;
}
class String
{
private:
char *m_data;
public:
String(const char *str)
{
if(str==NULL)
{
m_data=new char[1];
assert(m_data!=NULL);
m_data='\0';
}
else
{
int len=m_strlen(str);
m_data=new char[len+1];
assert(m_data!=NULL);
m_strcpy(m_data,str);
}
}
String(const String &other )
{
int len=m_strlen(other.m_data);
m_data=new char[len+1];
assert(m_data!=NULL);
m_strcpy(m_data,other.m_data);
}
~String()
{
delete []m_data;
}
String& operator=(const String &other)
{
if(this==&other)
{
return *this;
}
delete []m_data;
int len=m_strlen(other.m_data);
m_data=new char[len+1];
m_strcpy(m_data,other.m_data);
return *this;
}
String& operator+=(const String &other)
{
int len=m_strlen(m_data)+m_strlen(other.m_data)+2;
char *pstr=new char[len];
m_strcpy(pstr,m_data);
strcat(pstr,other.m_data);
*this=String(pstr);
return *this;
}
String operator+(const String &other)
{
int len=m_strlen(m_data)+m_strlen(other.m_data)+2;
char *pstr=new char[len];
m_strcpy(pstr,m_data);
strcat(pstr,other.m_data);
return String(pstr);
}
friend ostream& operator<<(ostream &out,const String& s )
{
if(s.m_data!=NULL)
{
out<<s.m_data<<endl;
}
return out;
}
};
void main()
{
String str1("hello");
String str2(str1);
String str3("weiqian");
String str4("today");
str4=str1+str3;
cout<<str4;
}
String类基本操作
最新推荐文章于 2022-04-12 11:34:08 发布