仿照string类,完成myString 类
#include <iostream>
#include <cstring>
#define MAX 10
using namespace std;
class myString
{
private:
char *str;
int size;
public:
//无参构造
myString():str(new char[MAX]),size(MAX)
{
strcpy(str, "");
cout<<"无参构造"<<endl;
}
//有参构造
myString(const char *s)
{
this->size = strlen(s);
this->str = new char[size+1];
strcpy(str, s);
cout<<"有参构造"<<endl;
}
//拷贝构造
myString (const myString &other):str(new char[other.size+1]),size(other.size)
{
strcpy(this->str, other.str);
cout<<"拷贝函数"<<strlen(str)<<endl;
}
//析构函数
~myString()
{
delete [] str;
cout<<"析构函数"<<endl;
}
//拷贝赋值函数
myString & operator = (const myString &other)
{
if(this != &other)
{
this->size = other.size;
if(this->str != NULL)
{
delete [] this->str;
}
this->str = new char[*other.str];
strcpy(str, other.str);
}
cout<<"拷贝赋值函数"<<strlen(str)<<endl;
return *this;
}
//判空函数
bool mystring_empty()
{
if(strlen(str) == 0)
{
return true;
}
return false;
}
//size函数
void mystring_size()
{
if(mystring_empty() == true)
{
cout<<"实际长度为size ="<<strlen(str)<<endl;
return ;
}
cout<<"实际长度为size = "<<strlen(str)<<endl;
return ;
}
//c_str函数
const char* c_str(myString s)const
{
char *ptr = new char[s.size+1];
strcpy(ptr, str);
return ptr;
}
//at函数
//cahr &at(int pos)
//加号运算符重载
const myString operator+(const myString &s1)
{
int newsize = this->size+s1.size;
char *ptr = new char[newsize+1];
strcpy(ptr, str);
strcat(ptr, s1.str);
cout<<ptr<<endl;
return ptr;
}
//加等于运算符重载
myString &operator+=(const myString &other)
{
int newsize = this->size+other.size;
char *newptr = new char[newsize+1];
strcpy(newptr, other.str);
strcat(newptr, str);
cout<<newptr<<endl;
return *this;
}
//关系运算符重载(<)
//中括号运算符重载
};
int main()
{
myString s1("hello world");
myString s2 = s1;
myString s3("chen");
myString s4 = s3;
s4+=s1;
myString s5;
s5=s2+s1;
return 0;
}