程序设计实习MOOC / 继承和派生——编程作业 第五周程序填空题1

博客介绍了如何在C++中从标准string类派生出MyString类,并实现特定的加法运算符重载,以解决编程作业中的问题。内容包括对operator+的分析,以及为何需要重写父类的operator+以返回子类对象。还提到了string的c_str()函数和复制构造函数的重要性。
摘要由CSDN通过智能技术生成
描述

写一个MyString 类,使得下面程序的输出结果是:

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-

要 求:MyString类必须是从C++的标准类string类派生而来。提示1:如果将程序中所有 "MyString" 用"string" 替换,那么题目的程序中除了最后两条语句编译无法通过外,其他语句都没有问题,而且输出和前面给的结果吻合。也就是说,MyString类对 string类的功能扩充只体现在最后两条语句上面。提示2: string类有一个成员函数 string substr(int start,int length); 能够求从 start位置开始,长度为length的子串

程序:

    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    using namespace std;

// 在此处补充你的代码

    int CompareString( const void * e1, const void * e2) {
        MyString * s1 = (MyString * ) e1;
        MyString * s2 = (MyString * ) e2;
        if( *s1 < *s2 )     return -1;
        else if( *s1 == *s2 ) return 0;
        else if( *s1 > *s2 ) return 1;
    }
    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 << "
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值