程序设计与算法(三)第五周测验(2018春季) 2:继承自string的MyString
题目网址:http://cxsjsxmooc.openjudge.cn/2018t3springw5/2/
【题目描述】
程序填空,输出指定结果
1 #include <cstdlib> 2 #include <iostream> 3 #include <string> 4 #include <algorithm> 5 using namespace std; 6 class MyString:public string 7 { 8 // 在此处补充你的代码 9 }; 10 11 12 int main() 13 { 14 MyString s1("abcd-"),s2,s3("efgh-"),s4(s1); 15 MyString SArray[4] = {"big","me","about","take"}; 16 cout << "1. " << s1 << s2 << s3<< s4<< endl; 17 s4 = s3; 18 s3 = s1 + s3; 19 cout << "2. " << s1 << endl; 20 cout << "3. " << s2 << endl; 21 cout << "4. " << s3 << endl; 22 cout << "5. " << s4 << endl; 23 cout << "6. " << s1[2] << endl; 24 s2 = s1; 25 s1 = "ijkl-"; 26 s1[2] = 'A' ; 27 cout << "7. " << s2 << endl; 28 cout << "8. " << s1 << endl; 29 s1 += "mnop"; 30 cout << "9. " << s1 << endl; 31 s4 = "qrst-" + s2; 32 cout << "10. " << s4 << endl; 33 s1 = s2 + s4 + " uvw " + "xyz"; 34 cout << "11. " << s1 << endl; 35 sort(SArray,SArray+4); 36 for( int i = 0;i < 4;i ++ ) 37 cout << SArray[i] << endl; 38 //s1的从下标0开始长度为4的子串 39 cout << s1(0,4) << endl; 40 //s1的从下标5开始长度为10的子串 41 cout << s1(5,10) << endl; 42 return 0; 43 }
输入
无
输出
1. abcd-efgh-abcd- 2. abcd- 3. 4. abcd-efgh- 5. efgh- 6. c 7. abcd- 8. ijAl- 9. ijAl-mnop 10. qrst-abcd- 11. abcd-qrst-abcd- uvw xyz about big me take abcd qrst-abcd-
【提示】
提示 1:如果将程序中所有 "MyString" 用 "string" 替换,那么除
了最后两条红色的语句编译无法通过外,其他语句都没有问题,而且输出和前
面给的结果吻合。也就是说,MyString 类对 string 类的功能扩充只体现在最
后两条语句上面。
提示 2: string 类有一个成员函数 string substr(int start,int
length); 能够求从 start 位置开始,长度为 length 的子串
提示 3: C++中,派生类的对象可以赋值给基类对象,因为,一个派生
类对象,也可看作是一个基类对象(大学生是学生)。反过来则不行(学生未
必是大学生) 同样,调用需要基类对象作参数的函数时,以派生类对象作为实参,也是没有问题的
【题解】
1 class MyString:public string 2 { 3 public: 4 MyString() : string("") { 5 } 6 MyString(const char* a) :string(a) { 7 } 8 MyString(const MyString & rhs) :string(rhs) {} 9 friend ostream& operator<<(ostream& o, const MyString& a) { 10 o << string(a); 11 return o; 12 } 13 MyString& operator=(const MyString& a) { 14 this->assign(a.data()); 15 return *this; 16 } 17 char& operator[](int i) { 18 return this->at(i); 19 } 20 friend MyString operator+(const MyString& a, const MyString& b) { 21 string c = string(a) + string(b); 22 return MyString(c.data()); 23 } 24 friend MyString operator+(const char* a, const MyString& b) { 25 MyString temp(a); 26 return temp + b; 27 } 28 friend MyString operator+(const MyString& b, const char* a) { 29 MyString temp(a); 30 return b + temp; 31 } 32 void operator +=(const char *a) { 33 this->append(a); 34 } 35 string operator()(int a, int l) { 36 string c = this->substr(a, l); 37 return c; 38 } 39 };