#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
friend ostream& operator<<(ostream& L, const my_string& o);
my_string():str(NULL)
{
cout<<"这是一个无参构造函数"<<endl;
}
my_string(char *str, int len)
{
this->str = str;
this->len = len;
cout<<"这是一个有参构造函数"<<endl;
}
~my_string()
{
delete str;
str = NULL;
cout<<"这是一个析构函数"<<endl;
}
my_string(const my_string& other)
{
this->len = other.len;
this->str = new char[other.len+1];
char *p = this->str;
char *q = other.str;
int i = 0;
for(i=0; i<len; i++)
{
*(p++) = *(q++);
}
cout<<"这是一个深拷贝构造函数"<<endl;
}
my_string& operator=(const my_string& other)
{
if(&other != this)
{
this->len = other.len;
if(this->str != NULL)
{
delete []this->str;
this->str = NULL;
}
this->str = new char[len+1];
int i = 0;
char *p = this->str;
char *q = other.str;
for(i=0; i<len; i++)
{
*(p++) = *(q++);
}
}
cout<<"这是一个深拷贝赋值函数"<<endl;
return *this;
}
my_string operator+(const my_string& a)const
{
my_string temp;
temp.len = this->len + a.len;
temp.str = new char[temp.len+1];
strcpy(temp.str, this->str);
strcat(temp.str, a.str);
cout<<"这是一个+运算符重载函数"<<endl;
return temp;
}
char operator[](int n)
{
cout<<"这是一个[]运算符重载函数"<<endl;
return this->str[n];
}
char* show()
{
return str;
}
bool my_empty()
{
if(str == NULL)
return false;
else
return true;
}
int my_size()
{
return len;
}
};
ostream& operator<<(ostream& L, const my_string& o)
{
L<<o.str<<" "<<o.len;
cout<<"这是一个插入运算符重载函数";
return L;
}
int main()
{
// my_string stu1("cdq",3);
// cout<<stu1.show()<<endl;
// my_string stu2(stu1);
// cout<<stu2.show()<<endl;
// my_string stu3;
// stu3 = stu2;
// cout<<stu3.show()<<endl;
// cout<<stu3.my_empty()<<endl;
// cout<<stu3.my_size()<<endl;
my_string s1("cdq", 3);
my_string s2("zjf", 3);
my_string s3 = s1 + s2;
cout<<s3.show()<<endl;
cout<<s3<<endl;
cout<<s3[2]<<endl;
}