String.h
#ifndef STRING_H
#define STRING_H
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
String(); //默认构造函数
String(const char *str); //构造函数:C字符串初始化
String(const String &str); //构造函数:String类对象初始化
~String();
String& operator =(const char *str); //重载赋值运算符:C字符串初始化
String& operator =(const String &str); //重载赋值运算符:String类对象初始化
char& operator [](unsigned int index); //重载[]运算符:可修改元素
const char& operator[](unsigned int index) const; //重载[]运算符:不可修改元素
String operator +(const String &str); //重载+运算符
friend bool operator <(const String &str1, const String &str2); //重载<运算符
friend bool operator >(const String &str1, const String &str2); //重载>运算符
friend bool operator ==(const String &str1, const String &str2); //重载==运算符
friend ostream& operator <<(ostream &os, const String &str); //重载<<运算符
friend istream& operator >>(istream &os, const String &str); //重载>>运算符
private:
char *m_str;
};
#endif // STRING_H
String.cpp
#include "String.h"
String::String()
{
m_str = new char[1];
m_str[0] = '\0';
}
String::String(const char *str)
{
m_str = new char[strlen(str) + 1];
strcpy(m_str, str);
}
String::String(const String &str)
{
m_str = new char[strlen(str.m_str) + 1];
strcpy(m_str, str.m_str);
}
String& String::operator =(const char *str)
{
delete [] m_str; //删除旧的str空间
m_str = new char[strlen(str) + 1];
strcpy(this->m_str, str);
return *this;
}
String& String::operator =(const String &str)
{
if (this == &str)
{
return *this; //将自身赋值给自身
}
delete [] m_str; //删除旧的str空间
m_str = new char[strlen(str.m_str) + 1];
strcpy(this->m_str, str.m_str);
return *this;
}
String String::operator +(const String &str)
{
String tempStr;
if (!str.m_str)
{
return *this;
}
else if (!this->m_str)
{
return str;
}
else
{
tempStr.m_str = new char[strlen(this->m_str) + strlen(str.m_str) + 1];
strcpy(tempStr.m_str, this->m_str);
strcpy(tempStr.m_str, str.m_str);
return tempStr;
}
}
char& String::operator [](unsigned int index)
{
return this->m_str[index];
}
const char& String::operator[](unsigned int index) const
{
return this->m_str[index];
}
bool operator <(const String &str1, const String &str2)
{
if (strcmp(str1, str2) < 0)
{
return true;
}
else
{
return false;
}
}
bool operator >(const String &str1, const String &str2)
{
if (strcmp(str1, str2) > 0)
{
return true;
}
else
{
return false;
}
}
bool operator ==(const String &str1, const String &str2)
{
if (strcmp(str1, str2) == 0)
{
return true;
}
else
{
return false;
}
}
ostream& operator <<(ostream &os, const String &str)
{
os << str.m_str << endl;
return os;
}
istream& operator >>(istream &is, const String &str)
{
char temp[100];
is.get(temp, 100);
if (is)
{
is = str;
}
while (is && is.get() != '\n')
{
continue;
}
return is;
}
String::~String()
{
delete [] m_str;
}