类的问题请教
程序代码:
#include <iostream.h> #include <string.h> class yang { public: yang(); yang(const char *const); yang(const yang&); ~yang(); char & operator[](unsigned short offset); char operator[](unsigned short offset)const; yang operator+(const yang&); void operator+=(const yang&); yang& operator=(const yang&); unsigned short getlen()const{return itslen;} const char* getyang(){return itsyang;} private: yang(unsigned short); char *itsyang; unsigned short itslen; }; yang::yang() { itsyang= new char[1]; itsyang[0]='\0'; itslen=0; } yang::yang(unsigned short len) { itsyang=new char[len+1]; for(unsigned short i=0; i<len; i++) itsyang[i]='\0'; itslen=len; } yang::yang(const char * const cyang) { itslen=strlen(cyang); itsyang=new char[itslen+1]; for(unsigned short i=0;i<itslen; i++) itsyang[i]=cyang[i]; itsyang[itslen]='\0'; } yang::yang(const yang&rhs) { cout <<"iiii\n"; itslen=rhs.getlen(); itsyang=new char[itslen+1]; for(unsigned short i=0; i<itslen; i++) itsyang[i]=rhs[i]; itsyang[itslen]='\0'; } yang::~yang() { delete[]itsyang; itslen=0; } yang& yang::operator=(const yang &rhs) { if(this ==&rhs) return *this; delete[]itsyang; itslen=rhs.getlen(); itsyang=new char[itslen+1]; for(unsigned short i=0; i<itslen; i++) itsyang[i]=rhs[i]; itsyang[itslen]='\0'; return *this; } char &yang::operator[](unsigned short offset) { if(offset>itslen) { return itsyang[itslen-1]; } else { return itsyang[offset]; } } char yang::operator[](unsigned short offset)const { if(offset>itslen) { return itsyang[itslen-1]; } else { return itsyang[offset]; } } yang yang::operator +(const yang&rhs) { unsigned short totallen=itslen+rhs.getlen(); yang temp(totallen); unsigned short i; for(i=0; i<itslen; i++) temp[i]=itsyang[i]; for(unsigned short j=0;j<rhs.getlen(); j++,i++) temp[i]=rhs[j]; temp[totallen]='\0'; return temp; } void yang::operator+=(const yang&rhs) { unsigned short rhslen=rhs.getlen(); unsigned short totallen=itslen + rhslen; yang temp(totallen); unsigned short i; for(i=0;i<itslen; i++) temp[i]=itsyang[i]; for(unsigned short j=0; j<rhs.getlen(); j++,i++) temp[i]=rhs[j]; temp[totallen]='\0'; *this=temp; } int main() { yang s1("adfgfgdgdgdfgfda"); cout << "s1:\t" << s1.getyang() << endl; char *temp ="bqdqdwqdqdqdqwdqqwdwqdqdwqdqdwqqwdqddwkkkkkbaaaa"; // 为什么这里超过39个字符就不输出cout << "s1:\t" << s1.getyang() << endl; cout << "s1:\t" << s1.getyang() << endl; char temptwo[20]; strcpy(temptwo,"cc"); s1+=temptwo; cout << "temptwo:\t" << temptwo << endl; cout << "s1:\t" << s1.getyang() << endl; cout << "s1[4]:\t" << s1[3] <<endl; s1[5]='x'; cout << "s1:\t" << s1.getyang() << endl; cout << "s1[999];\t" << s1[999] << endl; yang s2("dd"); yang s3; s3=s1+s2; //这里为什么会调用复制函数 cout << "s3:\t" << s3.getyang() << endl; yang s4; s4 ="ee"; cout << "s4:\t " << s4.getyang() << endl; return 0; }