#include <iostream>
using namespace std;
class MyString
{
public:
friend ostream& operator<<(ostream& os, MyString& str);
friend istream& operator>>(istream& is, MyString& str);
MyString()
{
m_len = 0;
m_str = nullptr;
}
//创建一个长度是len的string对象
MyString(int len)
{
m_len = len;
m_str = new char[m_len + 1];
memset(m_str, 0, len + 1);
}
MyString(const char* str)
{
m_len = strlen(str);
m_str = new char[m_len + 1];
strcpy(m_str, str);
}
//拷贝构造函数
MyString(const MyString& other)
{
if (nullptr != this->m_str)
{
delete this->m_str;
this->m_str = nullptr;
}
this->m_len = other.m_len;
this->m_str = new char[this->m_len + 1];
strcpy(this->m_str, other.m_str);
}
~MyString()
{
if(nullptr == m_str)
{
return;
}
delete m_str;
m_str = nullptr;
}
//[]操作符重载
char operator[](int index)
{
char zimu = m_str[index];
return zimu;
}
// = 运算符重载
MyString& operator=(MyString& other)
{
//避免自身赋值
if(this == &other)
{
return *this;
}
this->m_len = other.m_len;
this->m_str = new char[(this->m_len) + 1];
strcpy(this->m_str, other.m_str);
return *this;
}
// == 操作符重载
bool operator==(MyString& other)
{
int ret = strcmp(this->m_str, other.m_str);
if(ret == 0)
{
return true;
}
else
{
return false;
}
}
private:
int m_len;
char* m_str;
};
//cout操作符重载
ostream& operator<<(ostream& os, MyString& str)
{
os << str.m_str;
return os;
}
//cin 操作符重载
istream& operator>>(istream& is, MyString& str)
{
if(nullptr != str.m_str)
{
delete str.m_str;
str.m_str = nullptr;
}
char s[1024] = {0};
cout << "请输入字符串:";
cin >> s;
str.m_len = strlen(s);
str.m_str = new char[str.m_len + 1];
strcpy(str.m_str, s);
return is;
}
int main()
{
MyString s1("hello world!");
MyString s2(s1);
cout << s2 << endl;
return 0;
}