String类的部分实现和测试

来源:互联网 发布:ithink系统动力学软件 编辑:程序博客网 时间:2024/06/05 13:28
#include<iostream>
#include<string.h>
using namespace std;
class String{
public:
String(const char *b="\0")
{
a=new char[strlen(b)+1];
strcpy(a,b);
}
String(const String &A)
{
a=new char[strlen(A.a)+1];
strcpy(a,A.a);
}
String operator=(const String &A)
{
a=new char[strlen(A.a)+1];
strcpy(a,A.a);
return A;
}
String operator+(const String &A)
{
String B;
B.a=new char[strlen(a)+strlen(A.a)+1];
strcpy(B.a,a);
strcat(B.a,A.a);
return B;
}
~String()
{
delete []a;
a=NULL;
}
friend ostream& operator<<(ostream &out,const String &A);
friend istream& operator>>(istream &in,const String &A);
private:
char* a;
};


ostream& operator<<(ostream &out,const String &A)
{
out<<A.a;
return out;
}
istream& operator>>(istream &in,const String &A)
{
in>>A.a;
return in;
}


int main()
{
String A("I Love ");
String B("China.");
String C; 
C=A+B;
cout<<"A: "<<A<<endl;
cout<<"B: "<<B<<endl;
cout<<"A+B: "<<C<<endl;
String D;
cout<<"请输入一个字符串:" ;
cin>>D;
cout<<"输入的字符串:"<<D<<endl; 
return 0;
}