面向对象程序设计 lab15 学号 班级 姓名
1、= = 、> 、< 属于双目运算符,在重载双目运算符时,函数中应该有两个参数。 2、String类成员变量应为字符型指针; 3、多个构造函数的定义;
#include
protected: char *sp; public:
string(){sp=0;} //构造函数 string(string &); //复制构造函数 string(char *s) //构造函数 {
sp=new char[strlen(s)+1]; strcpy(sp,s); }
~string (){if(sp)delete sp;} //析构函数 void show(){cout< string & operator = (string &); //赋值运算符重载 friend string operator + (string &,string &); //友元函数实现加法运算符重载 string operator - (string &); //一个字符串减去另一个字符串 string operator - (char); //一个字符串减去指定字符 int operator > (string &); //比较运算 }; string::string(string &s) 面向对象程序设计 lab15 学号 班级 姓名 { if(s.sp){ sp=new char[strlen(s.sp)+1]; strcpy(sp,s.sp); } else sp=0; } string operator + (string &s1,string &s2) { string t; t.sp=new char[strlen(s1.sp)+strlen(s2.sp)+1]; strcpy(t.sp,s1.sp); //字符串复制函数 strcat(t.sp,s2.sp); //字符串并接函数 return t; } string string::operator - (string &s) { string t1=*this; char *p; while(1) { if(p=strstr(t1.sp,s.sp)) //strstr()返回的是,s.sp第一次在t1.sp出现时候的位置,赋值给指针p { if(strlen(t1.sp)==strlen(s.sp)) //如果两个字符串完全相同 { delete t1.sp; //则全部删除 t1.sp=0; //把他的值赋值为0 break; //返回 } string t2; t2.sp=new char[strlen(t1.sp)-strlen(s.sp)+1]; char *p1=t1.sp,*p2=t2.sp; int i=strlen(s.sp); while(p1 while(i){p1++;i--;} //i是要删除的字符串的长度,p1要跳过这些字符; while(*p2++=*p1++); //后面的无论相不相同都储存下来,等下一次循环再作处理; t1=t2; } else break; } return t1; 面向对象程序设计 lab15 学号 班级 姓名 } string string::operator - (char s) { string t1; int i=0,flag=0; t1.sp=new char[strlen(sp)+1]; char *p1=sp,*p2=t1.sp; while(*p1) { if(*p1!=s){ *p2++=*p1++; i++; flag=1; } else p1++; } *p2='\\0'; return t1; } int string::operator > (string &s) { if(strcmp(sp,s.sp)>0) //strcmp()函数,作用是比较两个字符串的大小 { return 1; } else return 0; } string & string::operator = (string &s) //因为这个类中有指针对象,所以要自定义赋值运算符重载,注意这里要引用 { if(sp) delete sp; //先将原有的空间释放掉 if(s.sp) { sp=new char[strlen(s.sp)+1]; //再申请内存赋值 strcpy(sp,s.sp); } else sp=0; return *this; } void main() { string s1(\ s1.show(); s2.show(); 面向对象程序设计 lab15 学号 班级 姓名 s3=s1+s2; s3.show(); if(s1>s2) cout<<\成立!\ else cout<<\不成立!\ s4=s3-s2; s4.show(); s5=s3-'t'; s5.show(); } [测试数据] 1、 China china 2、 National Computer 3、 Examination Rank 4、 swust swust 3、异常处理 创建一个表示圆型的类Circle,其中包含表示半径的数据成员radius,当创建Circle类对象时,需要初始化具体对象的数据成员radius,如果使用一个小于零的值初始化对象的半径,则会出现运行时异常,使用C++异常处理机制捕获并处理这种可能产生的异常。 #include class circle { private: 面向对象程序设计 lab15 学号 班级 姓名 int r; public: void input() { cout<<\输入半径\ cin>>r; } double S() { return 3.14*r*r; } void output() { cout<<\半径: \面积: \ } }; void main() { circle circle11; double r,R; circle11.input(); circle11.S(); circle11.output(); }