3、 仿照标准字符串类string ,设计一个自己的字符串类String。
主要完成以下任务:
1)数据成员是字符指针,可自动适应不同的串长度。
2)串复制,既可使用字符串常量进行复制,也可以使用其他的字符串对象进行复制。
3)串赋值。既可赋值为字符串常量,也可以赋值为使用其他的字符串对象。
4)串连接。重载“+”和“+=”。
5)重载下标运算符[]。
6)串比较。重载 “”和“<”。
7)字符串输入和输出。重载“>>”和“<<”。
编程完成各函数的定义,并进行如下测试。
int main()
{
String s1(“Help!”),s2(“Good!”),s3(s2),s4,s5;
cout<<“s1=”<<s1<<endl;
s3=“Hello!”;
cout<<“s3=”<<s3<<endl;
s3=s2;
cout<<“s3=”<<s3<<endl;
s3+=s2;
cout<<“s3=”<<s3<<endl;
cin>>s4;
cout<<“s4=”<<s4<<endl;
s5=s3+s4;
cout<<“s5=”<<s5<<endl;
s5[0]=‘g’;
cout<<“s5=”<<s5<<endl;
cout<<“strlen(s5)=”<<s5.Length()<<endl;
cout<<boolalpha<<(s3s1)<<endl;
cout<<boolalpha<<(s3<s1)<<endl;
}
下面是代码
#include<iostream>
#include<cstring>
using namespace std;
class String
{
friend ostream & operator<<(ostream &cout, const String &s)
{
cout << s.str;
return cout; //cin,cout的重载,注意函数的返回值
}
friend istream & operator >>(istream &cin, String &s)
{
cin >> s.str;
if(cin)
return cin;
}
public:
String(const char* p="oidahnsinaskl" ) //构造函数