代码演示
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *cstr;
int len;
public:
//无参构造
My_string():cstr(NULL),len(0){}
//有参构造
My_string(const char* str)
{
len = strlen(str);
cstr = new char[len+1]();
strcpy(cstr,str);
}
//(深拷贝)拷贝构造
My_string(const My_string &other)
{
len = other.len;
cstr = new char[len+1]();
strcpy(cstr,other.cstr);
}
//(深拷贝)拷贝赋值(=)
My_string& operator=(const My_string &other)
{
if(this != &other)
{
len = other.len;
cstr = new char[len+1]();
strcpy(cstr,other.cstr);
}
return *this; //返回自身引用
}
//运算符重载(+)
My_string operator+(const My_string &r)const
{
My_string temp;
temp.len = this->len+r.len;
temp.cstr = new char[temp.len+1]();
strcat(temp.cstr,this->cstr);
strcat(temp.cstr,r.cstr);
//返回新的类对象
return temp;
}
//运算符重载(==)
bool operator==(const My_string &r)const
{
return !strcmp(this->cstr,r.cstr);
}
//运算符重载(!=)
bool operator!=(const My_string &r)const
{
return strcmp(this->cstr,r.cstr);
}
//运算符重载(>)
bool operator>(const My_string &r)const
{
return strcmp(this->cstr,r.cstr)>0?1:0;
}
//运算符重载(>=)
bool operator>=(const My_string &r)const
{
return strcmp(this->cstr,r.cstr)>=0?1:0;
}
//运算符重载(<)
bool operator<(const My_string &r)const
{
return strcmp(this->cstr,r.cstr)<0?1:0;
}
//运算符重载(<=)
bool operator<=(const My_string &r)const
{
return strcmp(this->cstr,r.cstr)<=0?1:0;
}
//析构函数
~My_string()
{
if(cstr!=NULL)
{
delete []cstr;
}
cout<<"析构函数"<< " 析构地址为:"<< this <<endl;
}
//判断是否为空
bool empty()
{
return len==0?1:0;
}
//返回字符串的长度
int size()
{
return len;
}
//定位函数
char &at(int index)
{
static char ch = -1;
if(index<0 || index >= len)
{
cout<<"定位错误!"<<endl;
return ch;
}
return *(cstr+index);
}
//转化为C风格字符串
char* c_str()
{
return cstr;
}
void show()
{
cout<<"cstr = "<<cstr<<endl;
cout<<"len = "<<len<<endl;
cout<< "类对象地址为:"<< this <<endl<<endl;
}
friend ostream &operator<<(ostream &L, const My_string &R);
friend istream &operator>>(istream &L,My_string &R);
};
//运算符重载(<<)
ostream &operator<<(ostream &L, const My_string &R)
{
L<<R.cstr;
return L;
}
//运算符重载(>>)
istream &operator>>(istream &L,My_string &R)
{
R.cstr = new char[256];
L>>R.cstr;
R.len = strlen(R.cstr);
return L;
}
int main()
{
My_string m1 = "How";
m1.show();
My_string m2(" old");
m2.show();
My_string m3("qqqq");
m3 = m1+m2;
m3.show();
My_string m4 = " are you!";
m4.show();
My_string m5;
m5 = m1+m4;
m5.show();
if(m1>m2)
{
cout<<"真"<<endl;
}
else
{
cout<<"假"<<endl;
}
cout<<m5<<endl;
My_string m6;
cin>>m6;
m6.show();
return 0;
}
运行示例