代码如下:
#include <iostream>
#include <string.h>
using namespace std;
class mystring
{
public:
int size=20;
char *str;
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;
}
~mystring()
{
delete str;
cout <<"析构完毕"<<endl;
}
};
int main()
{
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;
}
效果图如下: