封装string
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
private:
char *str;
int len;
public:
mystring():len(10)
{
str = new char[len];
strcpy(str,"");
}
mystring(const char *s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
}
//拷贝构造
mystring(const mystring & other):str(new char (*(other.str))),len(other.len)
{
}
//析构构造
~mystring()
{
delete str;
cout<<"析构函数"<<" "<<this<<endl;
}
void show()
{
cout << "str = " << str << endl;
}
//拷贝赋值函数
mystring &operator = (const mystring &other)
{
if(this != &other)
{
this->len = other.len;
this->str = new char[len+1];
strcpy(str,other.str);
}
return *this;
}
//判空函数
bool empty()
{
if(0 == *str)
{
cout << "空" << endl;
return false;
}
else
{
cout << "不空" << endl;
return true;
}
}
//size函数
int size()
{
int num = 0;
char *p = str;
while(*p != 0)
{
num++;
p++;
}
return num;
}
//c_str函数
char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
return str[pos];
}
//加号运算符重载
const mystring operator + (const mystring &r)const
{
mystring temp;
strcat(this->str,r.str);
strcpy(temp.str,this->str);
temp.len = this->len + r.len;
return temp;
}
//加等于运算符重载
mystring operator += (const mystring &r)
{
strcat(this->str,r.str);
this->len += r.len;
return *this;
}
//关系运算符重载
bool operator > (const mystring &r) const
{
int n = strcmp(this->str,r.str);
return n>0;
}
//关系运算符重载
bool operator < (const mystring &r) const
{
int n = strcmp(this->str,r.str);
return n<0;
}
//关系运算符重载
bool operator == (const mystring &r) const
{
int n = strcmp(this->str,r.str);
return n=0;
}
};
int main()
{
char *s1 = "hello";
mystring s2(s1);
s2.show();
s2.empty();
cout << "size = " << s2.size() << endl;
mystring s3("world");
s3.show();
mystring s4;
s4 = s2+s3;
s4.show();
cout << "size = " << s4.size() << endl;
s4 += s3;
s4.show();
cout << "size = " << s4.size() << endl;
if(s4>s3)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
if(s4<s3)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
if(s4==s3)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
return 0;
}