代码如下:
#include <iostream>
#include <string.h>
using namespace std;
class mystring
{
public:
int size=20;
char *str;
mystring(){};
mystring(int size):str(new char(size)+1)
{
cout << "构造函数" << endl;
};
mystring(char *buf)
{
this->size = strlen(buf);
str = new char(size);
strcpy(str,buf);
}
mystring(mystring &s):size(s.size)
{
cout<<"s2中的字符串大小为" <<this->size <<endl;
this->str = new char(size);
strcpy(this->str,s.str);
cout << "拷贝完毕 " <<endl;
}
const mystring operator= ( const mystring &buf )const
{
mystring s1;
s1.size = this->size;
s1.str = this->str;
return s1;
}
const mystring operator+(const mystring &buf)const
{
mystring s1;
s1.size +=buf.size;
strcpy(s1.str,buf.str);
return s1;
}
bool operator>(const mystring &buf)const
{
return (this->size > buf.size);
}
bool operator<(const mystring &buf)const
{
return (this->size < buf.size);
}
~mystring()
{
delete str;
cout <<"析构完毕 "<<endl;
}
};
int main()
{
//cout << "Hello World!" << endl;
//封装string
char buf[20];
cin >> buf;
cout << "s1中的字符串内容为" << buf <<endl;
int size = strlen(buf); //字符串大小
cout <<"s1中的字符串大小为" << size <<endl;
mystring s1(buf);
mystring s2 = s1;
cout << "s2中的字符串内容为" << s2.str <<endl;
return 0;
}