我申请了内存空间 ,但是没办法释放 在析构函数中用delete inside;的话就会在执行的时候出错
大家帮忙指出错误,请务必在改错后在自己的机器上运行下,看看有没问题 谢谢
目标:模拟string类,实现main函数中的指令
#include <iostream>
using namespace std;
class String
{
public:
String() { inside= new char(50);}//ok
String(char *get)
{
inside= new char(strlen(get));
for(int i=0;i<strlen(get);i++)
inside[i]=get[i];}
String(String& s1)
{
inside=new char (s1.length());
for(int i=0;i<s1.length()+1;i++)
*(inside+i)=*(s1.inside+i);
}//ok
int find(String& s2);
int length();//ok
~String () {}
void operator =(String& c1);//ok
String operator +(String& c2);//ok
friend istream& operator >>(istream &cin,String &o1);//ok
friend ostream& operator <<(ostream &cout,String &o2);//ok
bool operator > (String c3);//ok
bool operator < (String c4);//ok
char operator [](int x);//ok
int getx(int m,int n)
{
if(m>n)
return n;
else if (m<n)
return m;
else return 0;
}
private:
char *inside;
};
int String::find(String& s2)
{
for(int i=0;i<length();i++)
{
for(int j=i,k=0;k<s2.length()&&inside[j]==s2.inside[k];j++,k++) ;
if(k==s2.length())
return i;
}
return -1;
}
int String::length()
{
int len(0);
for(;inside[len]!='\0';len++)
;
return len;
}
void String::operator =(String& c1)
{
inside=c1.inside;
}
String String::operator +(String& c2)
{
String se(*this);
int t=length();
for(int nu=0;nu<c2.length()+1;nu++)
se.inside[nu+t]=c2.inside[nu];
return se;
}
istream& operator >>(istream& cin,String& o1)
{
cin>>o1.inside;
return cin;
}
ostream& operator <<(ostream& cout,String& o2)
{
cout<<o2.inside;
return cout;
}
bool String::operator >(String c3)
{
int leng=getx(length(),c3.length());
int g(0),h(0);
for(;inside[g]>=c3.inside[g];g++) ;
for(;inside[h]<=c3.inside[h];h++) ;
if(g>h)
return true;
else if(g<h)
return false;
else if(g==h)
{
if(length()>c3.length())
return true;
else return false;
}
else
return false;
}
bool String::operator <(String c4)
{
int leng=getx(length(),c4.length());
int g(0),h(0);
for(;inside[g]>=c4.inside[g];g++) ;
for(;inside[h]<=c4.inside[h];h++) ;
if(g>h)
return false;
else if(g<h)
return true;
else if(g==h)
{
if(length()<c4.length())
return true;
else return false;
}
else
return false;
}
char String::operator [](int x)
{
return *(inside+x);
}
int main()
{
String s1,s2,s3;
cin>>s1>>s2;
s3=s1+s2;
cout<<s3<<endl;
for(int i=0;i<s3.length();i++)
cout<<s3[i];
cout<<endl;
if(s1>s2)
cout<<s1<<" is more lager than "<<s2<<endl;
cout<<s3.find(s2);
return 0;
}