C++程序重载string类,使string类对象能进行+连接,cout输出 

设计一个字符串类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;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值