返回:贺老师课程教学链接
【项目-String类的构造】
写一个能处理字符串的类,其数据成员如下所示:
class String { public: ...//需要的成员函数(若需要的话,声明友元函数) private: char *p; //指向存储的字符串 int len; //记录字符串的长度 };
请构造String类的加、减运算。其中,s1 + s2将两个字符串的连接起来;s1 - s2是将s1的尾部空格和s2的前导空格去除后的连接。
提示:有指针成员,设计时要注意。这个,你懂的。
[参考解答]
#include <iostream> #include <Cstring> using namespace std; class String { public: String( ); //默认构造函数 String(const char *s); String(String &str); //构造函数 ~String(); void display( ); friend String operator + (String &s1,String &s2 ); friend String operator - (String &s1,String &s2 ); private: char *p; int len; //字符型指针,用于指向字符串 }; String::String() { len = 0; p = NULL; } String::String(const char *s) { len = strlen(s); p = new char[len+1]; strcpy(p,s); } String::String(String &str) { len = str.len; if(p!=NULL) delete []p; //当发生在赋值等情形时,原对象可能已经存在,需释放原有空间 p = new char[len+1]; strcpy(p,str.p); } String::~String() { if(!p) delete []p; } void String::display( ) //输出p所指向的字符串 { cout<<p<<endl; } String operator + (String &s1, String &s2 ) { String s; s.len = s1.len+s2.len; s.p = new char[s.len+1]; //原误写char(s.len+1) strcpy(s.p,s1.p); strcat(s.p,s2.p); return s; } String operator - (String &s1, String &s2 ) { String s; //c1为截去尾部空格的字符串 char *c1=new char[s1.len+1]; strcpy(c1,s1.p); int i=s1.len-1; while(i>=0&&c1[i]==' ') --i; c1[i+1]='\0'; //c2为去除前导空格的字符串 char *c2=new char[s2.len+1]; strcpy(c2,s2.p); i=0; while(i<s2.len&&c2[i]==' ') ++i; int j=0; while(i<s2.len&&c2[i]!='\0') { c2[j]=c2[i]; ++i; ++j; } c2[j]='\0'; //将这两部分接起来 s.len = strlen(c1)+strlen(c2); s.p = new char[s.len+1]; //原误写char(s.len+1) strcpy(s.p,c1); strcat(s.p,c2); delete c1; delete c2; return s; } int main( ) { String string1(" Hello "), string2(" World "); string1.display(); string2.display(); String string3; string3 = string1 + string2; string3.display(); string3 = string1 - string2; string3.display(); return 0; }
时间: 2024-09-20 12:40:06