String的运算符重载
String的运算符重载
主要对String类的=、< 、>、==、+、>>运算符进行重载
示例
class String {
public:
String(const char* p = nullptr)
{
if (p != nullptr)
{
_pstr = new char[strlen(p) + 1];
strcpy(_pstr, p);
}
else
{
_pstr = new char[1];
*_pstr = '\0';
}
}
String(const String& rhs)
{
_pstr = new char[strlen(rhs._pstr) + 1];
strcpy(_pstr, rhs._pstr);
}
String& operator=(const String& rhs)
{
if (this == &rhs)
return *this;
delete[]_pstr;
_pstr = new char[strlen(rhs._pstr) + 1];
strcpy(_pstr, rhs._pstr);
return *this;
}
bool operator<(const String& rhs)
{
return strcmp(_pstr, rhs._pstr) < 0;
}
bool operator>(const String& rhs)
{
return strcmp(_pstr, rhs._pstr) > 0;
}
bool operator==(const String& rhs)
{
return strcmp(_pstr, rhs._pstr) == 0;
}
String operator+(const String& str)
{
char* pstr = new char[strlen(_pstr) + strlen(str._pstr) + 1];
strcpy(pstr, _pstr);
strcat(pstr, str._pstr);
String tmp(pstr);
delete[]pstr;
return tmp;
}
char& operator[](int i)
{
return _pstr[i];
}
const char& operator[](int i)const
{
return _pstr[i];
}
friend ostream& operator <<(ostream& out, const String& str);
~String()
{
delete[]_pstr;
_pstr = nullptr;
}
private:
char* _pstr;
};
ostream& operator <<(ostream& out, const String& str)
{
out << str._pstr;
return out;
}