设计一个字符串类string,并完成以下功能
(1)能使用+运算符进行两个字符串的连接运算
(2)能使用=运算符进行两个字符的复制
(3)能显示一个字符串的值
(4)能计算字符串的长度
#include <iostream.h>
#define N 20
class mystring
{
public:char ch[N];
mystring(){for(int i=0;i<N;i++)
ch[i]=NULL;}
mystring(char *p)
{
for(int i=0;i<N;i++)
{
if(p!=NULL)
{ch[i]=*p;
p++;}
}
}
int ch_length();
friend mystring operator + (mystring &ch1,mystring &ch2);
friend ostream& operator << (ostream&,mystring&);
};
int mystring::ch_length()
{
int n=0;
for(int i=0;ch[i]!=NULL;i++)
n++;
return n;
}
ostream& operator << (ostream& output,mystring& ch1)
{
for (int i=0;i<ch1.ch_length();i++)
output<<ch1.ch[i];
return output;
}
mystring operator +(mystring &ch1,mystring &ch2)
{
mystring ch3;
if(ch1.ch_length()+ch2.ch_length()<=N)
{for(int i=0;i<ch1.ch_length();i++)
ch3.ch[i]=ch1.ch[i];
for(int j=0;j<ch2.ch_length();j++,i++)
ch3.ch[i]=ch2.ch[j];
}
if(ch1.ch_length()+ch2.ch_length()>N)
{cout<<"长度不够!"<<endl;
}
return ch3;
}
int main()
{mystring ch1,ch2("hello"),ch3("happy!!!!!"),ch4;
int k=0;
ch1=ch2+ch3;
ch4=ch2;
k=ch1.ch_length();
cout<<"/t/t字符串运算/t/t"<<endl<<endl;
cout<<"ch1's length="<<k<<" 求字符长度函数的调用"<<endl<<endl;
cout<<"ch2+ch3="<<ch1<<" 重载运算符+的运用"<<endl<<endl;
cout<<"ch2="<<ch2<<" 重载输出运算符的运用"<<endl<<endl;
cout<<"ch3="<<ch3<<" 重载输出运算符的运用"<<endl<<endl;
cout<<"ch4="<<ch4<<" 实现类对象赋值运算"<<endl<<endl;
return 0;
}