• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
7777lcc
博客园    首页    新随笔    联系   管理    订阅  订阅

狗的继承(派生与继承)

6-1 狗的继承

完成两个类,一个类Animal,表示动物类,有一个成员表示年龄。一个类Dog,继承自Animal,有一个新的数据成员表示颜色,合理设计这两个类,使得测试程序可以运行并得到正确的结果。

函数接口定义:

按照要求实现类

裁判测试程序样例:

/* 请在这里填写答案 */

int main(){
    Animal ani(5);
    cout<<"age of ani:"<<ani.getAge()<<endl;
    Dog dog(5,"black");
    cout<<"infor of dog:"<<endl;
    dog.showInfor();
}


 

输入样例:

无

输出样例:

age of ani:5
infor of dog:
age:5
color:black

代码

#include <iostream>
#include<cstring>
using namespace std;
class Animal{
private:
int age;
public:
Animal(int a){
age=a;
}
int getAge(){
return age;
}
};
class Dog:public Animal{
char *color;
public:
Dog(int a,const char *c):Animal(a){
color=new char[20];
strcpy(color,c);
}
void showInfor()
{
cout<<"age:"<<getAge()<<endl;
cout<<"color:"<<color;
}
};
int main()
{
Animal ani(5);
cout<<"age of ani:"<<ani.getAge()<<endl;
Dog dog(5,"black");
cout<<"infor of dog:"<<endl;
dog.showInfor();
}

posted @ 2023-04-24 19:38  卖核弹的小女孩~  阅读(69)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3