课程作业七

题目描述

  • 请将随机生成数字、表达式的部分设计成:一个Random基类,基类中有random()方法。并由该基类派生出RandomNumber类、RandomOperation类,继承并覆盖父类方法。
  • 学习简单工厂模式,思考能否将该模式运用到题目的第一点要求中。

作业要求

  • 体会继承和多态的思想
  • 发表一篇博客,博客内容为:提供本次作业的github链接,题目描述的代码部分的解释、简单工厂模式的学习。

github

基类

#include<iostream>
#include<ctime>
#include<stdlib.h>
using namespace std; class Random{ public: virtual void random(char num){ } };

 派生类

class RandomNumber:public Random
{
    int number;
    public:
        void random(char &num){
            srand((unsigned)time(NULL));
            number=rand()%11;
            num=(char)number+48;
        }
};

class RandomOperation:public Random
{
    char operation;
    public:
        void random(char &ope){
            srand((unsigned)time(NULL));
            int a=rand()%4;
            switch(a){
                case 0:operation='+';break;
                case 1:operation='-';break;
                case 2:operation='*';break;
                case 3:operation='/';
            }
            ope=operation;
        }
};

简单工厂

class SimpleRandomFactory
{
    public:
        static Random *creat_random(const string &choose)
        {
            if("number"==choose)
            {
                return new RandomNumber();
            }
            if("operation"==choose)
            {
                return new RandomOperation();
            }
        }
};

主函数调用

int main(){
    SimpleRandomFactory ovo;
    Random *n,*o;
    int num;char ope;
    n=ovo.creat_random("number");
    o=ovo.creat_random("operation");
    n->random(num);
    o->random(ope);
    cout<<num<<ope<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/qvq-qvq/p/6973863.html