#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str;
int size;
public:
myString():size(10)
{
str = new char[size];
strcpy(str, "");
}
//有参构造
myString(const char *s)
{
if (s == nullptr) //如果是空,则初始化空
{
size = 0;
str = new char[size];
strcpy(str, "");
}
else
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
}
}
//拷贝构造
myString (const myString &other)
{
this->size = other.size;
this->str = new char[size + 1];
strcpy(this->str, other.str);
}
//析构函数
~myString()
{
delete [] str;
}
//拷贝赋值函数
myString &operator= (const myString &other)
{
if (this != &other)
{
delete [] str; //由于需要重新申请空间,所以要释放之前使用的空间
this->size = other.size;
this->str = new char[size + 1];
strcpy(this->str, other.str);
}
return *this;
}
//判空函数
bool empty()
{
return size == 0;
}
//size函数
int str_len()
{
return size;
}
//c_str函数
char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if (pos >= 0 || pos < this->size)
{
return str[pos];
}
}
//成员函数实现加号运算符重载:
const myString operator+ (const myString &R) const
{
myString temp;
temp.size = this->size + R.size;
temp.str = new char[temp.size + 1];
*temp.str = '\0';
strcat(temp.str, this->str);
strcat(temp.str, R.str);
return temp;
}
//成员函数实现加号运算符重载:
myString &operator+= (const myString &R)
{
char *temp = this->str;
delete [] str; //由于需要重新申请空间,所以要释放之前使用的空间
this->size = R.size + this->size;
this->str = new char[this->size + 1];
strcpy(this->str, temp);
strcpy(this->str, R.str);
return *this;
}
//关系运算符重载(>)
bool operator> (const myString &R) const
{
if (strcmp(this->str, R.str) > 0)
{
return true;
}
else
{
return false;
}
}
};
int main()
{
//有参构造
myString s1("hello world");
cout << s1.c_str() << endl;
//拷贝构造
myString s2(s1);
cout << s2.c_str() << endl;
//拷贝赋值
myString s3;
s3 = s1;
cout << s3.c_str() << endl;
//+重写
myString s4 = s1 + s3;
cout << s4.c_str() << endl;
myString s5("He");
if (s1 > s5)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
return 0;
}