字符串类
定义字符串连接的友元函数有问题,怎么改啊#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
class String
{
private:
int length;
char* str;
public:
String();
String(char* str0);
String(const String& str0);
int size();
friend istream& operator>>(istream& in,String& str0);
friend ostream& operator<<(ostream& out,String& str0);
char& operator[](int index);
以下四个函数的实现有问题,得不到想要的结果,输出乱码
friend String& operator+(const String& str0,const String& str1);
friend String& operator+(const String& str0,const char* str1);
friend String& operator+=(String& str0,const String& str1);
friend String& operator+=(String& str0,const char* str1);
~String();
};
String::String()
{
length=1;
str=new char[length+1];
str[0]='A';
}
String::String(char* str0)
{
int len=0;
for(int i=0;str0[i]!='\0';i++)
{
len++;
}
length=len;
str=new char[length+1];
assert(str!='\0');
strcpy(str,str0);
}
String::String(const String& str0)
{
length=str0.length;
str=new char[length+1];
str=str0.str;
}
int String::size()
{
return this->length;
}
istream& operator>>(istream& in,String& str0)
{
in>>str0.str;
str0.length=strlen(str0.str);
return in;
}
ostream& operator<<(ostream& out,String& str0)
{
out<<str0.str;
return out;
}
char& String::operator[](int index)
{
if(index>=0&&index<=size())
{
return this->str[index];
}
}
String& operator+(const String& str0,const String& str1)
{
String str2;
str2.length=str1.length+str0.length;
str2.str=new char[str2.length+1];
strcpy(str2.str,str0.str);
strcat(str2.str,str1.str);
return str2;
}
String& operator+(const String& str0,const char* str1)
{
String str2;
str2.length=strlen(str1)+str0.length;
str2.str=new char[str2.length+1];
strcpy(str2.str,str0.str);
strcat(str2.str,str1);
return str2;
}
String& operator+=(String& str0,const String& str1)
{
String str2;
str2.length=str1.length+str0.length;
str2.str=new char[str2.length+1];
strcpy(str2.str,str0.str);
strcat(str2.str,str1.str);
str0=str2;
return str0;
}
String& operator+=(String& str0,const char* str1)
{
String str2;
str2.length=strlen(str1)+str0.length;
str2.str=new char[str2.length+1];
strcpy(str2.str,str0.str);
strcat(str2.str,str1);
str0=str2;
return str0;
}
String::~String()
{
delete[] this->str;
}
int main()
{
String k;
cin>>k;
cout<<k<<endl;
cout<<k.size()<<endl;
String x("ZhangQian");
cout<<x<<endl;
cout<<x.size()<<endl;
String y(x);
cout<<y<<endl;
cout<<y.size()<<endl;
String a="WangYun";
cout<<a<<endl;
cout<<a.size()<<endl;
String b=x;
cout<<b<<endl;
cout<<b.size()<<endl;
char c=x[1];
cout<<c<<endl;
cout<<x<<endl;
a[2]='c';
cout<<y<<endl;
cout<<a<<endl;
String aa=x+k;
cout<<aa<<endl;
cout<<aa.size()<<endl;
char* ddd="SuXiaoLing";
String dddd=k+ddd;
cout<<dddd<<endl;
cout<<dddd.size()<<endl;
String zhangqian="ZhangQian";
zhangqian+=dddd;
cout<<zhangqian<<endl;
zhangqian+="wangyun";
cout<<zhangqian<<endl;
cout<<zhangqian.size()<<endl;
return 0;
}