#定义一个MyString类,实现两个字符串相加。要求定义类的数据成员为字 符指针,实现深拷贝函数。
要求:不能使用<string>
,可以使用<cstring>
include<iostream>
#include<cstring>
using namespace std;
class MyString
{public:
MyString();
MyString(const char *s);
MyString(const MyString &s);
void MyStrcat(MyString &s);
void display();
private:
char *str;
};
MyString::MyString()
{
this->str=new char[10];
str[0]='\0';
}
MyString::MyString(const char *s)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}
MyString::MyString(const MyString&s)//拷贝
{
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
}
void MyString::MyStrcat(MyString &s)
{
int i,j;
char *s1=new char[strlen(str)+1];
strcpy(s1,str);
str=new char[strlen(str)+strlen(s.str)+1];
for(i=0;i<strlen(s1);i++)
str[i]=s1[i];
for(j=0;j<strlen(s.str);j++)
str[i++]=(s.str)[j];
str[i]='\0';
delete[]s1;
}
void MyString::display()
{
cout<<str<<endl;
}
int main()
{
MyString str1("Hello ");
MyString str2("World!");
MyString str3(str1);
str1.display();
str2.display();
str3.display();
str1.MyStrcat(str2);
str2.MyStrcat(str1);
str1.display();
str2.display();
str3.display();
return 0;
}
小团子敲代码,愉快呀~