你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / C专栏
C++继承——宠物的生长
 

以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
版权声明:本文为博主原创文章,转载请附上博文链接!

  推荐精品文章

·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 
·2023年7月目录
·2023年6月目录 
·2023年5月目录
·2023年4月目录 
·2023年3月目录 
·2023年2月目录 
·2023年1月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089