北京市公租房车位标准:C++高手来帮下忙~重载运算符+-*/最好带注释~万分火急

来源:百度文库 编辑:神马品牌网 时间:2024/04/28 15:36:53
C++高手来帮下忙~重载运算符+-*/最好带注释~万分火急
我只有25分
重载 + - * / = << >>

#include "stdafx.h"
#include <iostream.h>
#include <conio.h>
#include <string.h>
#define MAXLENGTH 256
class CString
{
protected:
char *ptr;
int length;
public:
CString() {ptr=NULL; length=0;}
CString(const char *str)
{
length=strlen(str);
if (length==0) {ptr=NULL; return;}
ptr=new char [length];
memcpy(ptr,str,length);
}
CString(const CString &r)
{
length=r.length;
if (ptr!=NULL) delete []ptr; ptr=NULL;
if (r.ptr==NULL) return;
ptr=new char[length];
memcpy(ptr,r.ptr,length);
}
~CString() {if (ptr!=NULL) delete []ptr; }
int GetLength() const{ if (ptr==NULL) return 0; return length;}
void Lowercase()
{
if (ptr==NULL) return;
char *tmp=ptr;
for (int i=0;i<length;i++)
{
char c=*tmp;
if (c>='A' && c<='Z') c+='a'-'A';
*tmp++=c;
}
}
char *Left(char *buf,int n) const
{
if (ptr==NULL) return NULL;
if (n>length) n=length;
memcpy(buf,ptr,n);
buf[n]='\0';
return buf;
}
bool operator ==(const CString &t) const
{
if (t.ptr==NULL && ptr==NULL) return true;
if (t.ptr==NULL || ptr==NULL) return false;
if (length!=t.length) return false;
return 0==memcmp(ptr,t.ptr,length);
}
char operator [](int i) const
{
if (ptr==NULL) return '\0';
if (i>=length) return '\0';
return ptr[i];

}
friend ostream &operator <<(ostream &cout, const CString &r);
friend istream &operator >>(ostream &in, CString &r);
const CString &operator =(CString &r)
{
if (ptr!=NULL) delete [] ptr;
ptr=NULL; length=r.length;
if (r.ptr==NULL) return *this;
ptr=new char [length];
memcpy(ptr,r.ptr,length);
return *this;
}
const CString &operator +(CString &r)
{
if (r.ptr==NULL) return *this;
char *temp;
int l=length+r.length;
temp=new char [l];
if (ptr!=NULL) {
memcpy(temp,ptr,length);
delete [] ptr;}
memcpy(temp+length,r.ptr,r.length);
ptr=temp; length=l;
return *this;
}

friend istream &operator >>(istream &in, CString &r);
friend ostream &operator <<(ostream &cout, const CString &r);

};
ostream &operator <<(ostream &out, const CString &r)
{
if (r.ptr==NULL) return out;
char *temp=new char [r.length+1];
memcpy(temp,r.ptr,r.length);
temp[r.length]='0';
out<<temp;
delete []temp;
return out;
}

istream &operator >>(istream &in, CString &r)
{
char str[MAXLENGTH];
in>>str;
if (r.ptr!=NULL) delete []r.ptr;
r.ptr=NULL; r.length=0;
r.length=strlen(str);
if (r.length==0) return in;
r.ptr=new char [r.length];
memcpy(r.ptr,str,r.length);
return in;
}