以Pet为基类,构建出Cat和Dog两个类: Cat一天身长加1,体重加2。 Dog一天身长加2,体重加1。
class Pet { protected: string name;//姓名 int length;//身长 int weight;//体重 int current;//当前日期 public: virtual void display(int day)=0;//输出目标日期的身长和体重 }
主函数根据输入的信息,相应建立Cat类对象或Dog类对象,并给出目标日期宠物的身长和体重。 输入格式:每个测试用例占一行,每行给出宠物的基本信息,第一个为当前宠物的类型:1为Cat,2为Dog。接下来为它的名字,随后的两个数字为身长和体重,最后为测身长和体重的日期(不大于10的正整数)。最后一行为目标日期(大于10的正整数)。 要求输出目标日期宠物姓名、身长和体重
#include "stdafx.h" #include <iostream> #include <string> using namespace std; class Pet { protected: string name;//姓名 int length;//身长 int weight;//体重 int current;//当前日期 public: Pet(string n, int l, int w, int c) :name(n), length(l), weight(w), current(c) {}; virtual void display(int day) = 0;//输出目标日期的身长和体重 }; class Cat:public Pet { public: Cat(string n, int l, int w, int c) :Pet(n, l , w, c) {}; void display(int day) { int x = day - current; length += x; weight += 2 * x; cout << name << " "<< length << " "<< weight <<" "<< endl; } }; class Dog:public Pet { public: Dog(string n, int l, int w, int c) :Pet(n, l, w, c) {}; void display(int day) { int x = day - current; length += 2 * x; weight += 2; cout << name << " " << length << " " << weight <<" "<< endl; } }; int main() { Pet *pt[10]; string n; int type, l, w, c; int count = 0; while (cin >> type) { if (type != 1 && type != 2) break; switch (type) { case 1: count++; cin >> n >> l >> w >> c; if (c > 10) break; pt[count - 1] = new Cat(n, l, w, c); break; case 2: count++; cin >> n >> l >> w >> c; if (c > 10) break; pt[count - 1] = new Dog(n, l, w, c); break; } } for (int i = 0; i<count; i++) { pt[i]->display(type); } system("pause"); return 0; } --------------------- 作者:GISer_rookie 来源:CSDN 原文:https://blog.csdn.net/GISer_rookie/article/details/84483453 版权声明:本文为博主原创文章,转载请附上博文链接!
|