#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class MyString
{
public:
MyString(const char *str=NULL);
MyString(const MyString &other);
~MyString();
MyString &operator= (const MyString &other);
MyString operator+ (const MyString &str) const; //MyString + MyString
friend ostream &operator<< (ostream&, MyString&);
friend istream &operator>> (istream&, MyString&);
friend MyString operator+ (const char *str1, const MyString &str2); //"abcd" + MyString
friend MyString operator +(const MyString &str1, const char *str2); //MyString + "abcd"
private:
char *m_data;
};
MyString::MyString(const char *str)
{
if (str == NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
size_t length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
}
MyString::MyString(const MyString &other)
{
size_t length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
MyString::~MyString(void)
{
delete []m_data;
m_data = NULL;
}
MyString & MyString::operator= (const MyString &other)
{
if (this == &other)
{
return *this;
}
delete [] m_data;
size_t length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
MyString MyString::operator + (const MyString &str) const
{
MyString temp;
temp.m_data = new char[strlen(this->m_data) + strlen(str.m_data) + 1];
strcpy(temp.m_data, this->m_data);
strcat(temp.m_data, str.m_data);
return temp;
}
ostream & operator<< (ostream &out, MyString &str)
{
out << str.m_data;
return out;
}
istream &operator>>( istream &input, MyString &s )
{
char temp[ 255 ];
input>>setw(255)>>temp;
s = temp;
return input;
}
MyString operator +(const char *str1, const MyString &str2)
{
MyString temp;
if (str1 == NULL)
{
temp = str2;
}
else
{
size_t length = strlen(str1) + strlen(str2.m_data);
temp.m_data = new char[length + 1];
strcpy(temp.m_data, str1);
strcat(temp.m_data, str2.m_data);
}
return temp;
}
MyString operator +(const MyString &str1, const char *str2)
{
MyString temp;
if (str2 == NULL)
{
temp = str1;
}
else
{
size_t length = strlen(str1.m_data) + strlen(str2);
temp.m_data = new char[length + 1];
strcpy(temp.m_data, str1.m_data);
strcat(temp.m_data, str2);
}
return temp;
}
int main()
{
MyString a = "aaa";
MyString b(a);
MyString c;
c = b;
cout<<"a="<<a<<"\n"<<"b="<<b<<endl<<"c="<<c<<endl;
cout<<"please input a string to a:";
cin>>a;
cout<<"a="<<a<<endl;
MyString d;
d = "str" + d;
cout<<"d="<<d<<endl;
d = "00" + a + "--" + b + "--" + c + "00";
cout<<d<<endl;
return 0;
}
C++模拟String类的一部分
最新推荐文章于 2022-09-26 18:00:14 发布