狗的继承(派生与继承)

发布时间 2023-04-24 19:44:05作者: 卖核弹的小女孩~
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();
}