代码:
#include <iostream>
#include <string.h>
using namespace std;
class MyString
{
private:
char *str;
int size;
public:
MyString():size(10) //无参构造函数
{
str=new char[size];
strcpy(str,"");
}
MyString(const char *s) //有参构造函数
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
MyString(const MyString& other):size(other.size) //拷贝构造函数
{
str=new char[size+1];
strcpy(str,other.str);
cout<<"拷贝构造"<<endl;
}
MyString& operator=(const MyString &other) //拷贝赋值函数
{
this->str=new char[size+1];
this->size=other.size;
strcpy(str,other.str);
return *this;
}
bool isempty() //判空函数
{
if(size==0)
{
return true;
}
else
{
return false;
}
}
int getsize() //得到字符串长度
{
return size;
}
char *c_str() //得到字符串
{
return str;
}
char &at(int pos) //输出具体位置的字符
{
return str[pos-1];
}
const MyString operator+ (const MyString &R)const //运算符+重构
{
MyString temp;
temp.str=strcat(this->str,R.str);
temp.size=this->size+R.size;
return temp;
}
MyString & operator+=(const MyString &R) //运算符+=重构
{
this->size=this->size+R.size;
this->str=strcat(this->str,R.str);
return *this;
}
bool operator>(const MyString &R)const //运算符>重构
{
if(strcmp(this->str,R.str))
return true;
else
return false;
}
~MyString(){}
};
int main()
{
MyString m1("hello");
MyString m2;
m2=m1;
cout<<m2.c_str()<<endl;
m1+=m2;
cout<<m1.c_str()<<endl;
MyString m3;
m3=m1+m2;
cout<<m3.c_str()<<endl;
if(m1>m2)
{
cout<<"m1>m2"<<endl;
}
cout<<m1.at(8)<<endl;
cout << "Hello World!" << endl;
return 0;
}
思维导图