class String
{
private:
char *m_data;
public:
String(const char *str = NULL);//默认构造函数
String(const String& other);//拷贝构造函数
~String();//析构函数
String &operator=(const String&other);//重载赋值运算符
bool operator==(const String&other);//重载equals运算符
String operator+(const String&other);//重载连接运算符
char &operator[](int index);//重载下标访问运算符
friend ostream& operator<<(ostream& out , const String& str);//重载输出运算符
friend istream& operator>>(istream& in , String& str);//重载输入运算符
size_t size()const{
return strlen(m_data);
}
};
String::String(const char *str)
{
if(NULL == str){
m_data = new char[1];
*m_data = '\0';
}else{
m_data = new char[strlen(str)+1];
strcpy(m_data , str);
}
}
String::String(const String& other)
{
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data , other.m_data);
}
String::~String()
{
delete []m_data;
}
String& String::operator=(const String&other)
{
if(this != &other){
if(NULL != m_data)
delete []m_data;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data , other.m_data);
}
return *this;
}
bool String::operator==(const String&other)
{
int len1 = this->size();
int len2 = other.size();
return strcmp(m_data , other.m_data)?false:true;
}
String String::operator+(const String&other)
{
int len1 = this->size();
int len2 = other.size();
String newStr;
newStr.m_data = new char[len1+len2+1];
strcpy(newStr.m_data , m_data);
strcat(newStr.m_data,other.m_data);
return newStr;
}
char &String::operator[](int index)
{
assert(index>=0 && index<this->size());
return m_data[index];
}
ostream& operator<<(ostream& out , const String& str)
{
out<<str.m_data;
return out;
}
istream& operator>>(istream& in , String& str)
{
char buffer[1024];
char c;
int i=0;
while((c=in.get())!='\n'){
buffer[i++] = c;
}
buffer[i] = '\0';
if(NULL != str.m_data)
delete []str.m_data;
str.m_data = new char[i+1];
strcpy(str.m_data , buffer);
return in;
}