#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char *str = "");//有参构造
MyString(const MyString &other);//拷贝构造
~MyString();//析构
MyString &operator=(const char *str);//重载=
MyString &operator=(const MyString &otther);//重载=
char &operator[](unsigned int index);//重载[]
friend ostream &operator<<(ostream &os, MyString &str);
friend istream &operator>>(istream &is, MyString &str);
private:
char *m_str;
};
MyString::MyString(const char * str)//有参构造
{
if (NULL == str)
{
this->m_str = new char[1]{ 0 };
}
else
{
int len = strlen(str);
this->m_str = new char[len + 1]{ 0 };
strcpy(this->m_str, str);
}
}
MyString::MyString(const MyString &other)
{
if (NULL == other.m_str)
{
this->m_str = new char[1]{ 0 };
}
else
{
int len = strlen(other.m_str);
this->m_str = new char[len + 1]{ 0 };
strcpy(this->m_str, other.m_str);
}
}
MyString::~MyString()
{
if (this->m_str != NULL)
{
cout << "析构" << endl;
delete[]this->m_str;
this->m_str = NULL;
}
}
MyString &MyString::operator=(const char *str)
{
if (NULL == this->m_str)
{
delete[]this->m_str;
}
if (NULL == str)
{
this->m_str = new char[1]{ 0 };
}
else
{
int len = strlen(str);
this->m_str = new char[len + 1];
strcpy(this->m_str, str);
}
return *this;
}
MyString &MyString::operator=(const MyString &other)
{
if (this == &other)//自身赋值
{
return *this;
}
if (this->m_str != NULL)
{
delete[]this->m_str;
}
if (NULL == other.m_str)
{
this->m_str = new char[1]{ 0 };
}
else
{
int len = strlen(other.m_str);
this->m_str = new char[len + 1]{ 0 };
strcpy(this->m_str, other.m_str);
}
return *this;
}
#if 0
operator[]//不抛异常
at()//会抛异常
#endif
char &MyString::operator[](unsigned int index)
{
return this->m_str[index];
}
ostream &operator<<(ostream &os, MyString &str)
{
os << str.m_str;
return os;
}
istream &operator >>(istream &is, MyString &str)
{
char buf[100] = { 0 };
if (str.m_str != NULL)
{
delete[]str.m_str;
}
is >> buf;//接受用户的信息
int len = strlen(buf);
str.m_str = new char[len + 1]{ 0 };
strcpy(str.m_str, buf);
return is;
}
void main()
{
MyString s1("hi");//有参构造
MyString s2(s1);//拷贝构造 旧值初始化新值
MyString s3("ABin");
cout <<"有参构造:"<< s1 << endl;
cout <<"拷贝构造:" <<s2 << endl;
cout << "....:" << s3 << endl;
//s3.~MyString();//析构
s2 = s3;
cout << "operator= : " << s2 << endl;
s1 = "abin";
cout << "字符串operator= : " << s1 << endl;
MyString s4;
cin >> s4;
cout << s4 << " 分割 :" << s4[2] << endl;
}
实现String类
最新推荐文章于 2022-05-25 10:54:09 发布