#include <iostream>
#include <cstring>
#include <assert.h>
using namespace std;
class String
{
public:
String()
{
char *m_pstr = new char[1];
m_pstr[0] = '\0';
}
String(const char *pstr)
{
assert(pstr != NULL);
m_pstr = new char[strlen(pstr) + 1];
strcpy(m_pstr, pstr);
}
String(const String & rhs)
{
m_pstr = new char[strlen(rhs.m_pstr) + 1];
strcpy(m_pstr, rhs.m_pstr);
}
~String()
{
delete[]m_pstr;
m_pstr = NULL;
}
String & operator=(const String & rhs)
{
if (this != &rhs)
{
delete[] m_pstr;
m_pstr = new char[strlen(rhs.m_pstr) + 1];
strcpy(m_pstr, rhs.m_pstr);
}
return *this;
}
String operator+(const String &rhs) const
{
String newString;
if (!rhs.m_pstr)
newString = *this;
else if (!m_pstr)
newString = rhs;
else
{
newString.m_pstr = new char[strlen(m_pstr) + strlen(rhs.m_pstr) + 1];
strcpy(newString.m_pstr, m_pstr);
strcat(newString.m_pstr, rhs.m_pstr);
}
return newString;
}
char operator [](const unsigned int index)
{
if (index >= 0 && index<strlen(m_pstr))
return m_pstr[index];
else
{
cout << "Error: the index of [] is invalid." << endl;
exit(0);
}
}
friend ostream& operator<<(ostream & output, const String &rhs)
{
output << rhs.m_pstr;
return output;
}
friend istream& operator>>(istream& is, String& rhs)
{
char temp[255];
is >> temp;
rhs = temp;
return is;
}
bool operator==(const String& rhs)
{
if (strlen(m_pstr) != strlen(rhs.m_pstr))
return false;
else
return strcmp(m_pstr,rhs.m_pstr) ? false : true;
}
size_t size() const
{
return strlen(m_pstr);
}
const char* c_str() const
{
return m_pstr;
}
private:
char *m_pstr;
};
String类实现
最新推荐文章于 2022-04-12 11:34:08 发布