• 5-2 宠物的生长(多态)


    现在要开发一个系统,对宠物的生长状态进行管理。 给出下面的一个基类框架 class Pet { protected:   string name;//姓名 int length;//身长 int weight;//体重 int current;//当前日期 public: virtual void display(int day)=0;//输出目标日期的身长和体重 } 以Pet为基类,构建出Cat和Dog两个类: Cat一天身长加1,体重加2。 Dog一天身长加2,体重加1。 生成上述类并编写主函数,要求主函数中有一个基类Pet指针数组,数组元素不超过10个。 Pet *pt[10]; 主函数根据输入的信息,相应建立Cat类对象或Dog类对象,并给出目标日期宠物的身长和体重。

    提示:应用虚函数实现多态

    输入格式:

    每个测试用例占一行,每行给出宠物的基本信息,第一个为当前宠物的类型:1为Cat,2为Dog。接下来为它的名字,随后的两个数字为身长和体重,最后为测身长和体重的日期(不大于10的正整数)。最后一行为目标日期(大于10的正整数)

    输出格式:

    输出目标日期宠物姓名、身长和体重

    输入样例:

    1 Marry 22 12 5
    2 Jack 10 9 9
    1 Jim 11 8 6
    11
    

    输出样例:

    Marry 28 24
    Jack 14 11
    Jim 16 18




    #include<iostream>
    using namespace std;
    class Pet{
    protected:
        string name;
        int height;
        int weight;
        int current;
    public:
        Pet(string a,int b,int c,int d):name(a),height(b),weight(c),current(d){};
        virtual void grow(int day) = 0;
        virtual void display() = 0;
    };
    class Cat : public Pet {
    public:
        Cat(string a,int b,int c,int d):Pet(a,b,c,d){};
        void grow(int day){
            int x = day - current;
            height+=x;
            weight+=2*x;
        }
        void display(){
            cout<<name<<" "
                <<height<<" "
                <<weight<<endl;
        }
    };
    class Dog : public Pet {
    public:
        Dog(string a,int b,int c,int d):Pet(a,b,c,d){};
        void grow(int day){
            int x=day-current;
            height+=2*x;
            weight+=x;
        }
        void display(){
            cout<<name<<" "
                <<height<<" "
                <<weight<<endl;
        }
    };
    int main()
    {
        Pet *p[100];
        string name;
        int type,h,w,r;
        int count=0;
        while(cin>>type)
        {
            
            if(type!=1 && type!=2) break;
            count++;
            cin>>name>>h>>w>>r;
            switch(type){
            case 1:
                p[count-1] = new Cat(name,h,w,r);
                break;
            case 2:
                p[count-1] = new Dog(name,h,w,r);
                break;    
            }
        }
        for(int i=0;i<count;i++)
        {
            p[i]->grow(type);
            p[i]->display();
        }
        return 0;
    }
    个人分享,欢迎指导,未经允许,请勿转载。谢谢!
  • 相关阅读:
    位运算
    UNIQUE VISION Programming Contest 2022(AtCoder Beginner Contest 248)
    Educational Codeforces Round 127 (Rated for Div. 2) 题解AE
    Google Code Jam Round 1B 2022
    MapReduce编程实践(Hadoop3.1.3)
    Flink安装与编程实践(Flink1.9.1)
    HBase2.2.2安装和编程实践指南
    HDFS编程实践
    Spark安装和编程实践(Spark2.4.0)
    Hive3.1.2安装指南
  • 原文地址:https://www.cnblogs.com/hello-OK/p/7020300.html
Copyright © 2020-2023  润新知