• 宠物的生长(多态)


    现在要开发一个系统,对宠物的生长状态进行管理。 给出下面的一个基类框架 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 #include<iostream>
     2 #include<string>
     3 using namespace std;
     4 
     5 class Pet      //Pet类 抽象类 6 {
     7 protected:
     8     string name;
     9     int length,weight,current;
    10 public:
    11     virtual void display(int day)=0;  //虚函数 
    12     virtual ~Pet(){};
    13 };
    14 
    15 class Cat:public Pet
    16 {
    17 public:
    18     Cat(){};
    19     Cat(string N,int L,int W,int C);
    20     void display(int day);
    21 };
    22 
    23 Cat::Cat(string N,int L,int W,int C)  //初始化Cat类对象
    24 {
    25     name=N,length=L,weight=W,current=C;
    26 }
    27 
    28 void Cat::display(int day)  //重载虚函数
    29 {
    30     cout<<name<<" "<<length+(day-current)<<" "<<weight+(day-current)*2<<endl;
    31 }
    32 
    33 class Dog:public Pet
    34 {
    35 public:
    36     Dog(){};
    37     Dog(string N,int L,int W,int C);
    38     void display(int day);
    39 };
    40 
    41 Dog::Dog(string N,int L,int W,int C)  //初始化Dog类对象
    42 {
    43     name=N,length=L,weight=W,current=C;
    44 }
    45 
    46 void Dog::display(int day)
    47 {
    48     cout<<name<<" "<<length+(day-current)*2<<" "<<weight+(day-current)<<endl;
    49 }
    50 
    51 int main()
    52 {
    53     int flag,i(0);
    54     Pet *pt[10];
    55     string name;
    56     int length,weight,time;
    57     while(cin>>flag,flag==1||flag==2)  //输入flag,当flag==1或==2时执行
    58     {
    59         cin>>name>>length>>weight>>time;
    60         switch(flag)
    61         {
    62         case 1:pt[i++]=new Cat(name,length,weight,time);break;
    63         case 2:pt[i++]=new Dog(name,length,weight,time);break;
    64         }
    65     }
    66     for(int j(0);j<i;j++)
    67     {
    68         pt[j]->display(flag);
    69     }
    70     return 0;
    71 }
  • 相关阅读:
    c11---位运算相关
    c10---多文件开发
    C9---include,编译
    c8---递归
    c7---函数
    c6----函数的声明和实现
    c5
    Arm 环境上面libgdiplus的简单安装配置
    批量查找可执行文件目录的简单方法
    Android常用工具类
  • 原文地址:https://www.cnblogs.com/wzzdeblog/p/10777840.html
Copyright © 2020-2023  润新知