首页 > 其他分享 >020:继承自string的MyString

020:继承自string的MyString

时间:2022-08-28 17:13:42浏览次数:90  
标签:const string 020 基类 MyString include

(21条消息) C++面向对象程序设计 020:继承自string的MyString ---- (北大Mooc)(含注释)_Love 6的博客-CSDN博客

 1 #include <cstdlib>
 2 #include <iostream>
 3 #include <string>
 4 #include <algorithm>
 5 using namespace std;
 6 class MyString:public string
 7 {
 8 public:
 9     MyString(const char* str):string(str){}
10     MyString(const MyString& s):string(s){} //派生类给基类成员(str)赋值 
11     MyString(const string& s):string(s){} ///*对于+号 那些 基类含+号函数 默认对基类的字符串相加 之后的出来的值 再用类型转换函数 将 相加所返回的字符串再做类型转换函数 转换为MYString类型*/
12     MyString():string(){}
13     friend ostream& operator<<(ostream& o,const string& s){ //用派生类实参,输出基类成员(这个重载本来可以不写的,写是为了理解“调用需要基类对象作参数的函数时,以派生类对象作为实参,也是没有问题的”) 
14         o << s; //!!!这里是输出s而不是s.str,因为你并不知道基类函数string里的函数成员叫什么 ,不一定就是叫str 
15         return o;
16     }
17     MyString operator()(int start,int length){//这里返回类型是MyString而不是char*,原因同上 
18         MyString res(substr(start,length)); //创建res并用 substr(start,length) 来初始化它 
19         return res;
20     }
21 };
22 
23 
24 int main()
25 {
26     MyString s1("abcd-"),s2,s3("efgh-"),s4(s1);
27     MyString SArray[4] = {"big","me","about","take"};
28     cout << "1. " << s1 << s2 << s3<< s4<< endl;
29     s4 = s3;
30     s3 = s1 + s3;
31     cout << "2. " << s1 << endl;
32     cout << "3. " << s2 << endl;
33     cout << "4. " << s3 << endl;
34     cout << "5. " << s4 << endl;
35     cout << "6. " << s1[2] << endl;
36     s2 = s1;
37     s1 = "ijkl-";
38     s1[2] = 'A' ;
39     cout << "7. " << s2 << endl;
40     cout << "8. " << s1 << endl;
41     s1 += "mnop";
42     cout << "9. " << s1 << endl;
43     s4 = "qrst-" + s2;
44     cout << "10. " << s4 << endl;
45     s1 = s2 + s4 + " uvw " + "xyz";
46     cout << "11. " << s1 << endl;
47         sort(SArray,SArray+4);
48     for( int i = 0;i < 4;i ++ )
49     cout << SArray[i] << endl;
50     //s1的从下标0开始长度为4的子串
51     cout << s1(0,4) << endl;
52     //s1的从下标5开始长度为10的子串
53     cout << s1(5,10) << endl;
54     return 0;
55 }

 

标签:const,string,020,基类,MyString,include
From: https://www.cnblogs.com/balabalabubalabala/p/16633099.html

相关文章