实现一个字符串类
- 构造函数要求:
MyString a;
MyString a("dasfa");
MyString b = a;
- 常用的操作符: << >> != == > < =
- C语言中,没有字符串这种类型,是通过数组来模拟字符串;C++中我们来设计一个字符串 ,以零结尾的字符串
- MyString.h
#include<iostream>
using namespace std;
class MyString
{
friend ostream& operator<<(ostream &out,MyString &s);
private:
int m_len; char *m_p;
public://构造析构函数
MyString(int len = 0);
MyString(const char *p);
MyString(const MyString& s);
~MyString();
public://重写 =
Mystring &opareator=(const MyString &s);
MyString& operatir=(const char*p);
char& operator[](int index);
public://重写 ==
bool operator==(const MyString& s);
bool operator!=(char *p);
};
- MyString.cpp
#include"MyString.h"
ostream& operator<<(ostream &out,MyString &s)
{
out<<s.m_p;
return out;
}
MyString::MyString(int len)
{
if(len == 0)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p,"");
}
else
{
m_len = len;
m_p = new char[m_len + 1];
strcpy(m_p,"");
}
}
MyString::MyString(const char *p)
{
if(p == NULL)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p,"");
}
else
{
m_len = strlen(p);
m_p = new char[m_len + 1];
strcpy(m_p,p);
}
}
MyString::MyString(MyString const &s)
{
m_len = s.m_len;
m_p = new char[m_len + 1];
strcpy(m_p,s.m_p);
}
MyString::~MyString()
{
if(m_p != NULL)
{
delete[]m_p;
m_p = NULL;
m_len = 0;
}
}
MyString& MyString::operator=(const MyString &s)
{
if(m_p != NULL)
{
delete[]m_p;
m_len = 0;
}
m_len = s.m_len;
m_p = new char [m_len + 1];
strcpy(m_p,s.m_p);
return *this;
}
MyString& MyString::operator=(char *p)
{
if(m_p != NULL)
{
delete[]m_p;
m_len = 0;
}
if(p == NULL)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p,"");
}
else
{
m_len = strlen(p);
m_p = new char[m_len +1 ];
strcpy(m_p,p);
}
return *this;
}
char& MyString::operator[](int index)
{
return m_p[index];
}
bool operator==(const MyString& s)
{
if(m_len == s.m_len)
{
return true;
}
return strcmp(m_p,s.m_p);
}
bool operator!=(char *p)
{
if(p == NULL)
{
if(m_len == 0)
{
return false;
}
else
{
return true;
}
}
else
{
if(m_len != strlen(p))
{
return strcmp(m_p,p);
}
else
{
return true;
}
}
return false;
}
- MyStringTest.cpp
#include<iostream>
using namespace std;
#include"MyString.h"
void main01()
{
MyString s1;
MyString s2("s2");
MyString s3 = s2;
MyString s4 = "s4444";
s4 = s2;
s4 = "s44";
s4[3] = '8';
cout<<s4<<endl;
system("pause");
}
void main02()
{
MyString s1;
MyString s2("s2");
MyString s3 = s2;
if(s3 == s2)
{
printf("相等\n");
}
else
{
printf("不相等\n");
}
if(s3 != s2)
{
printf("不相等\n");
}
else
{
printf("相等\n");
}
system("pause");
}