自己的STRING类

#include
#include
using namespace std;

class CSTRING
{
private:
char *p;
public:
CSTRING();
CSTRING(const char a[]);
CSTRING(CSTRING &a);
~CSTRING(){delete p;}
CSTRING operator =(const CSTRING &a);
CSTRING operator =(const char a[]);
CSTRING operator +=(CSTRING &a);
CSTRING operator +(CSTRING &a);
char& operator [](int i);
bool operator ==(CSTRING &a);
bool operator <(CSTRING &a);
friend istream& operator >> (istream &in,CSTRING &a);
friend ostream& operator << (ostream &out,CSTRING &a);
int Length(){return strlen§;}
};

CSTRING::CSTRING()
{
p=new char1;
}

CSTRING::CSTRING(const char a[])
{
int i=strlen(a);
p=new chari+1;
strcpy(p,a);
}

CSTRING::CSTRING(CSTRING &a)
{
int i=strlen(a.p);
p=new char i+1;
strcpy(p,a.p);
}

CSTRING CSTRING::operator = (const CSTRING &a)
{
delete p;
int i=strlen(a.p);
p=new char i+1;
strcpy(p,a.p);
return *this;
}

CSTRING CSTRING::operator =(const char a[])
{
delete p;
int i=strlen(a);
p=new chari+1;
strcpy(p,a);
return *this;
}

char& CSTRING::operator [](int i)
{
return p[i];
}

CSTRING CSTRING::operator +(CSTRING &a)
{
int k=0;
int i=strlen§;
int j=strlen(a.p);
CSTRING b;
delete b.p;
b.p=new char [i+j+1];
for(k=0;k<i;k++)
b.p[k]=p[k];
strcat(b.p,a.p);
return b;
}

CSTRING CSTRING::operator += (CSTRING &a)
{
int i=strlen§;
int j=strlen(a.p);
int k=0;
char *s=new chari+1;
char *m=new charj+1;
strcpy(m,a.p);
strcpy(s,p);
delete p;
p=new chari+j+1;
for(k=0;k<i;k++)
p[k]=s[k];
strcat(p,m);
delete s;
delete m;
return *this;
}

bool CSTRING::operator ==(CSTRING &a)
{
if(strcmp(p,a.p)==0)
return true;
return false;
}

bool CSTRING::operator <(CSTRING &a)
{
if(strcmp(p,a.p)<0)
return true;
return false;
}

istream& operator >> (istream &in,CSTRING &a)
{
char* a1=new char[1024];
in>>a1;
int i=strlen(a1);
delete a.p;
a.p=new char[i+1];
strcpy(a.p,a1);
return in;
}

ostream& operator << (ostream &out,CSTRING &a)
{
out<<a.p;
return out;
}

int main()
{
CSTRING 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;
s3+=s3;
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<<(s3==s1)<<endl;
cout<<boolalpha<<(s3<s1)<<endl;
}

有几个地方的确给我造成了不小的麻烦:
1.CSTRING CSTRING::operator = (const CSTRING &a)
这个地方的=的重载必须加const,因为在main函数中s5=s3+s4
而我们的s3+s4中,返回的是 return b;是一个临时变量,而在c++中有:
“临时变量不能作为非const引用参数,不是因为他是常量,而是因为c++编译器关于语义的限制。”
详见https://blog.csdn.net/kongying168/article/details/3864756

2.对于+=号的重载,一开始的确没考虑到自身加自身,所以在原来的写法中
delete p; p=new chari+j+1;
for(k=0;k<i;k++) p[k]=s[k];
strcat(p,a.p);
a.p就已经不存在了, strcat(p,a.p); 就是错误的写法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值