zoukankan      html  css  js  c++  java
  • 课程作业七

    题目描述

    • 请将随机生成数字、表达式的部分设计成:一个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;
    }
  • 相关阅读:
    Laravel中如何将单个routes.php分割成多个子文件
    PHP中“==”运算符的安全问题
    一些需要禁用的PHP危险函数
    使用PHP QR Code生成二维码
    gulp详细入门教程
    h5+分享到微信、朋友圈代码示例
    学习地址
    关于this 方法中套方法中找 立即执行的问题 等问题
    判断条件问题是否存在
    jsp 基础语法
  • 原文地址:https://www.cnblogs.com/qvq-qvq/p/6973863.html
Copyright © 2011-2022 走看看