北京大学MOOC C++程序设计 第五周测验

第五次课主要是学习的类的继承和派生,联系前面几次课学的类基础,构造函数,拷贝构造函数,析构函数,运算符重载等知识。

本周测试共4道题,其中第三道题 《魔兽世界* 装备》不要求提交。

第一道题:

1:全面的MyString

程序填空,输出指定结果

#include <cstdlib>
#include <iostream>
using namespace std;
int strlen(const char * s) 
{	int i = 0;
	for(; s[i]; ++i);
	return i;
}
void strcpy(char * d,const char * s)
{
	int i = 0;
	for( i = 0; s[i]; ++i)
		d[i] = s[i];
	d[i] = 0;
		
}
int strcmp(const char * s1,const char * s2)
{
	for(int i = 0; s1[i] && s2[i] ; ++i) {
		if( s1[i] < s2[i] )
			return -1;
		else if( s1[i] > s2[i])
			return 1;
	}
	return 0;
}
void strcat(char * d,const char * s)
{
	int len = strlen(d);
	strcpy(d+len,s);
}
class MyString
{
    //在这里补充你的代码;
};


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 << "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;
	qsort(SArray,4,sizeof(MyString),CompareString);
	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;
}

样例输入

样例输出

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-

首先从题干入手,题干中分别写了求字符串长度的strlen()方法,拷贝字符串的strcpy()方法,比较字符串的strcmp()方法和连接字符串的strcat()方法。其实现方法很简洁,值得学习。

int strlen(const char * s) 
{	int i = 0;
	for(; s[i]; ++i);
	return i;
}
void strcpy(char * d,const char * s)
{
	int i = 0;
	for( i = 0; s[i]; ++i)
		d[i] = s[i];
	d[i] = 0;
		
}
int strcmp(const char * s1,const char * s2)
{
	for(int i = 0; s1[i] && s2[i] ; ++i) {
		if( s1[i] < s2[i] )
			return -1;
		else if( s1[i] > s2[i])
			return 1;
	}
	return 0;
}
void strcat(char * d,const char * s)
{
	int len = strlen(d);
	strcpy(d+len,s);
}

尤其是重写的strcat()方法,赶紧记笔记。

void strcat(char * d,const char * s)
{
	int len = strlen(d);
	strcpy(d+len,s);
}

看着main函数的一堆操作,而MyString类全空,就知道需要补充很多东西。到底需要补充哪些,通过一条条语句来整理思路。

MyString s1("abcd-"),s2,s3("efgh-"),s4(s1); 这告诉我们需要补充无参构造函数,有参构造函数和拷贝构造函数。
cout << "1. " << s1 << s2 << s3<< s4<< endl;需要重载流提取运算符。 
s3 = s1 + s3;重载加法运算符
cout << "6. " << s1[2] << endl;重载[]运算符
s1 += "mnop";重载+=运算符。
s4 = "qrst-" + s2;重载加法运算符,注意这和s3 = s1 + s3;重载加法运算符不一样,所以加法运算符的有两个重载函数
cout << s1(0,4) << endl;重载(int,int)运算符
if( * s1 < *s2 )   if( *s1 == *s2)   if( *s1 > *s2 ) 重载小于 大于 等于比较运算符

梳理完毕后,我们依次进行编写。

    //三种构造函数
    MyString(){   //无参构造函数
        str = "";
    }
    MyString(const char * s){   //传入字符串为参数的构造函数
        if(s){
            str = new char[strlen(s) + 1];
            strcpy(str, s);
        }
        else
            str = NULL;
    }
    MyString(const MyString & s){       //拷贝构造函数
        str = new char[strlen(s.str) + 1];
        strcpy(str, s.str);
    }
    MyString operator()(int i, int j){   //重载()
        MyString res;                    //i为子串开始位置,j为子串长度
        res.str = new char[j];
        int start = i;
        int index = 0;
        for(index = 0; index < j; index++){
            res.str[index] = str[start++];
        }
        res.str[index] = '\0';
        return res;
    }
    char & operator[](int i){return str[i];}   //重载[]
    friend ostream& operator<<(ostream &os,const MyString &s){   //重载流提取运算符
        if(s.str == NULL)
            return os;
        else
        {
            os << s.str;
            return os;
        }
    }
    friend MyString operator+(const char * str, const MyString &rhs){  //这里重载加法运算
        MyString res(str);    //为了应对 "abcd" + s 的形式
        res = res + rhs;      //为什么采用友元,因为既可以应对 "abcd" + s
        return res;           //也可以应对s + "abcd";
    }
    MyString operator+(const MyString & rhs){  //重载加法运算符
        MyString res;
        int n = strlen(str) + strlen(rhs.str)+1;   //为了应对 s1 + s2 
        res.str = new char[n];
        strcpy(res.str, str);
        strcat(res.str, rhs.str);
        res.str[n-1] = '\0';
        return res;
    }
    MyString operator+=(const char * rhs){    //重载+=运算符
        MyString res;
        MyString r(rhs);
        res = *this + r;    //利用*this 简化编程
        *this = res;
        return *this;
    }
    //重载小于 大于 等于比较运算符
    bool operator < (const MyString & rhs){   
        int flag = strcmp(str, rhs.str);
        if(flag == -1)
            return true;
        else
            return false;
    }
    bool operator > (const MyString & rhs){
        int flag = strcmp(str, rhs.str);
        if(flag == 1)
            return true;
        else
            return false;
    }
    bool operator == (const MyString & rhs){
        int flag = strcmp(str, rhs.str);
        if(flag == 0)
            return true;
        else
            return false;
    }

值得学习的还有题目中写的比较函数

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;
}

所以完整答案为

#include <cstdlib>
#include <iostream>
using namespace std;
int strlen(const char * s)
{	int i = 0;
	for(; s[i]; ++i);
	return i;
}
void strcpy(char * d,const char * s)
{
	int i = 0;
	for( i = 0; s[i]; ++i)
		d[i] = s[i];
	d[i] = 0;

}
int strcmp(const char * s1,const char * s2)
{
	for(int i = 0; s1[i] && s2[i] ; ++i) {
		if( s1[i] < s2[i] )
			return -1;
		else if( s1[i] > s2[i])
			return 1;
	}
	return 0;
}
void strcat(char * d,const char * s)
{
	int len = strlen(d);
	strcpy(d+len,s);
}
class MyString
{
private:
    char * str;
public:
    MyString(){
        str = "";
    }
    MyString(const char * s){
        if(s){
            str = new char[strlen(s) + 1];
            strcpy(str, s);
        }
        else
            str = NULL;
    }
    MyString(const MyString & s){
        str = new char[strlen(s.str) + 1];
        strcpy(str, s.str);
    }
    MyString operator()(int i, int j){
        MyString res;
        res.str = new char[j];
        int start = i;
        int index = 0;
        for(index = 0; index < j; index++){
            res.str[index] = str[start++];
        }
        res.str[index] = '\0';
        return res;
    }
    char & operator[](int i){return str[i];}
    friend ostream& operator<<(ostream &os,const MyString &s){
        if(s.str == NULL)
            return os;
        else
        {
            os << s.str;
            return os;
        }
    }
    friend MyString operator+(const char * str, const MyString &rhs){
        MyString res(str);
        res = res + rhs;
        return res;
    }
    MyString operator+(const MyString & rhs){
        MyString res;
        int n = strlen(str) + strlen(rhs.str)+1;
        res.str = new char[n];
        strcpy(res.str, str);
        strcat(res.str, rhs.str);
        res.str[n-1] = '\0';
        return res;
    }
    MyString operator+=(const char * rhs){
        MyString res;
        MyString r(rhs);
        res = *this + r;
        *this = res;
        return *this;
    }
    bool operator < (const MyString & rhs){
        int flag = strcmp(str, rhs.str);
        if(flag == -1)
            return true;
        else
            return false;
    }
    bool operator > (const MyString & rhs){
        int flag = strcmp(str, rhs.str);
        if(flag == 1)
            return true;
        else
            return false;
    }
    bool operator == (const MyString & rhs){
        int flag = strcmp(str, rhs.str);
        if(flag == 0)
            return true;
        else
            return false;
    }
};


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 << "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;
	qsort(SArray,4,sizeof(MyString),CompareString);
	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;
}

第二道题为:

2:继承自string的MyString

程序填空,输出指定结果

#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;
}

样例输入

样例输出

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++中,派生类的对象可以赋值给基类对象,因为,一个派生类对象,也可看作是一个基类对象(大学生是学生)。反过来则不行(学生未必是大学生) 同样,调用需要基类对象作参数的函数时,以派生类对象作为实参,也是没有问题的

这道题和第一题的输入输出完全一样,关键是对String类的领悟。

提示里面有讲MyString 类对 string 类的功能扩充只体现在最后两条语句上面。那说明除了取子串的操作之外都是string类实现了的操作。

public:
    MyString():string(){}
    MyString(const MyString &A):string(A){}       
    MyString(const char * S):string(S){}
    MyString(const string & A):string(A){}    
    //类型转换构造函数, 把string对象转换成MyString 使得string 的+ 可以用  和最后的()可以用
    MyString operator()(int n, int m){
        return substr(n,m);
    }

所以最终答案为

#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class MyString:public string
{
public:
    MyString():string(){}
    MyString(const MyString &A):string(A){}       
    MyString(const char * S):string(S){}
    MyString(const string & A):string(A){}    
//类型转换构造函数, 把string对象转换成MyString 使得string 的+ 可以用  和最后的()可以用
    MyString operator()(int n, int m){
        return substr(n,m);
    }
};


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;
}

下一题:

4:编程填空:统计动物数量

描述

代码填空,使得程序能够自动统计当前各种动物的数量

#include <iostream>
using namespace std;
void print() {
	cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}

int main() {
	print();
	Dog d1, d2;
	Cat c1;
	print();
	Dog* d3 = new Dog();
	Animal* c2 = new Cat;
	Cat* c3 = new Cat;
	print();
	delete c3;
	delete c2;
	delete d3;
	print();
}

样例输入

None

样例输出

0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats

这个题和第三周的题目完全一样,考查的是类的继承,创建一个基类Animal类,派生类Dog和Cat类继承自Animal类,使用一个静态成员变量来统计数量。

class Animal
{
public:
    static int number;   //统计动物数量
    Animal()
    {
        number++;
    }
    virtual ~ Animal()   //基类析构函数添加virtual关键字 
    {
        number--;
    }
};
class Dog:public Animal
{
public:
    static int number;
    Dog()
    {
        number++;
    }
    ~Dog()
    {
        number--;
    }
};
class Cat:public Animal
{
public:
    static int number;
    Cat()
    {
        number++;
    }
    ~Cat()
    {
        number--;
    }
};
int Animal::number = 0;  //静态成员变量需要初始化
int Cat::number = 0;
int Dog::number = 0;

这里要注意的点就是:

程序中出现了
Animal* c2 = new Cat;
delete c2;
通过基类的指针删除派生类对象时,通常情况下只调用基类的析构函数
 但是,删除一个派生类的对象时,应该先调用派生类的析构函数,然后调用基类的析构函数。
 解决办法:把基类的析构函数声明为virtual
 派生类的析构函数可以virtual不进行声明
 通过基类的指针删除派生类对象时,首先调用派生类的析构函数,然后调用基类的析构函数
 一般来说,一个类如果定义了虚函数,则应该将析构函数也定义成虚函数。或者,一个类打算作为基类使用,也应该将析构函数定义成虚函数。
 注意:不允许以虚函数作为构造函数

猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/83042643