北大程序设计与算法(三)测验题汇总(2020春季)
描述
程序填空,输出指定结果
#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class MyString:public string
{
// 在此处补充你的代码
};
int main()
{
MyString s1("abcd-"),s2,s3("efgh-"),s4(s1);
MyString SArray[4] = {"big","me","about","take"};
cout << "1. " << s1 << s2 << s3<< s4<< endl;
s4 = s3;
s3 = s1 + s3;
cout << "2. " << s1 << endl;
cout << "3. " << s2 << endl;
cout << "4. " << s3 << endl;
cout << "5. " << s4 << endl;
cout << "6. " << s1[2] << endl;
s2 = s1;
s1 = "ijkl-";
s1[2] = 'A' ;
cout << "7. " << s2 << endl;
cout << "8. " << s1 << endl;
s1 += "mnop";
cout << "9. " << s1 << endl;
s4 = "qrst-" + s2;
cout << "10. " << s4 << endl;
s1 = s2 + s4 + " uvw " + "xyz";
cout << "11. " << s1 << endl;
sort(SArray,SArray+4);
for( int i = 0;i < 4;i ++ )
cout << SArray[i] << endl;
//s1的从下标0开始长度为4的子串
cout << s1(0,4) << endl;
//s1的从下标5开始长度为10的子串
cout << s1(5,10) << endl;
return 0;
}
输入
无
输出
- abcd-efgh-abcd-
- abcd-
- abcd-efgh-
- efgh-
- c
- abcd-
- ijAl-
- ijAl-mnop
- qrst-abcd-
- abcd-qrst-abcd- uvw xyz
about
big
me
take
abcd
qrst-abcd-
样例输入
无
样例输出
- abcd-efgh-abcd-
- abcd-
- abcd-efgh-
- efgh-
- c
- abcd-
- ijAl-
- ijAl-mnop
- qrst-abcd-
- 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++中,派生类的对象可以赋值给基类对象,因为,一个派生
类对象,也可看作是一个基类对象(大学生是学生)。反过来则不行(学生未
必是大学生) 同样,调用需要基类对象作参数的函数时,以派生类对象作为实参,也是没有问题的
来源
Guo Wei
分析
根据提示可知,string
是基类,MyString
是派生类;并且只需要重载()
即可。
那么如果只写一个重载()
是不是不太现实啊,如
string operator() ( int s, int l) {//重载()运算符
return substr(s,l);//string对象
};
此处因为返回的是substr(s,l)
这是string
类的对象,那么返回的类可能是string
基类,也可能是MyString
,因为将一个派生类指向基类也是合法的,所以此处有两种写法或者
MyString operator() ( int s, int l) {//重载()运算符
return substr(s,l);
};
除了重载之外,由于其他的都是一样的,那么直接继承就好。
- 无参构造函数
MyString():string() {}; //默认构造函数
- 有参构造函数
MyString( const char * s):string(s){}; //重载构造函数 ,此处相当于调用string类的构造函数
- 复制构造函数
MyString( const string & s ): string(s){};//复制构造函数
再者呢,完全不用担心其他运算符的重载,因为string类是满足+
,=
等重载的。
解答
class MyString:public string{
public:
MyString():string() {}; //默认构造函数
MyString( const char * s):string(s){}; //重载构造函数
MyString( const string & s ): string(s){};//复制构造函数
MyString operator() ( int s, int l) {//重载()运算符
return substr(s,l);
};
};