#include<iostream>
using namespace std;
class String
{
friend ostream& operator<< (ostream&,String&);
public:
String(const char* str=NULL); //赋值构造兼默认构造函数(char)
String(const String &other); //赋值构造函数(String)
String& operator=(const String&other); //operator=
String operator+(const String &other)const; //operator+
bool operator==(const String&); //operator==
char& operator[](unsigned int); //operator[]
size_t size(){return strlen(m_data);};
~String(void) {delete[] m_data;}
private:
char *m_data;
};
String::String(const char* str = NULL)
{
if(str == NULL)
m_data = 0;
m_data = new char[strlen(str)+1];
strcpy(m_data,str);
}
String::String(const String &other)
{
if(other.m_data == NULL)
m_data = 0;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data,other.m_data);
}
String &String::operator=(constr String &other)
{
if(this == other)
return *this;
delete[] m_data;
if(other.m_data == NULL)
m_data = 0;
else
{
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data,other.m_data);
}
return *this;
}
String String::operator+(constr String &other)
{
String tempStr;
if(other.m_data == NULL)
tempStr.m_data = *this;
else if(m_data == NULL)
tempStr = other;
else
{
tempStr.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];
strcpy(tempStr.m_data,m_data);
strcat(tempStr.m_data,other.m_data);
}
return tempStr;
}
bool String::operator==(const String &other)
{
if(strlen(m_data) != strlen(other.m_data))
return false;
return(strcmp(m_data,other.m_data)?false:true);
}
char& String::operator[](unsigned int n) //operator[]
{
if(n>=0 && n<=strlen(m_data)
return m_data[n];
}
Ostream &operator<<(Ostream &os,String &str)
{
os<<str.m_data;
return os;
}
void main()
{
String str1="Hello!";
String str2="World!";
String str3 = str1+str2;
cout<<str3<<endl<<str3.size()<<endl;
}