#include <iostream>
using namespace std;
class MyString
{
public:
MyString(const char* str = NULL);
MyString(const MyString &other);
~MyString();
MyString& operator = (const MyString& other);
friend ostream& operator <<(ostream& os, const MyString& other);
/*<<有两个参数,一个是输出流对象(我们常用的cout),还有就是要输出的东西。
例如:cout<<"haha";
也就是说<<的第一个参数必须是输出流对象。
在成员函数里实现<<重载,我们知道this会作为第一个参数,而这是不符合要求的。
>>类似!*/
friend istream& operator >>(istream& is, MyString& other);
private:
char *m_data;
};
MyString::MyString(const char* str)
{
if(str == NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int len = strlen(str);
m_data = new char[len + 1];
strcpy(m_data, str);
}
}
MyString::MyString(const MyString &other)
{
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
}
MyString::~MyString()
{
delete[] m_data;
}
MyString& MyString::operator = (const MyString& other)
{
if(this == &other)
{
return *this;
}
else
{
delete[] m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
return *this;
}
}
ostream& operator <<(ostream& os, const MyString& other)
{
os << other.m_data;
return os;
}
istream& operator >> (istream& is, MyString& other)
{
const int limit_string_size = 4096;
other.m_data = new char[limit_string_size];
is >> other.m_data;
return is;
}
int main()
{
MyString str,str1;
cin>>str;
cout<<str<<endl;
str1 = str;
cout<<str1;
return 0;
}
String 类的简单技巧实现
最新推荐文章于 2023-07-10 17:24:38 发布