题目要求
完成两个类,一个类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>
using namespace std;
class Animal
{
public:
Animal() {} // 默认构造函数,不进行任何操作
Animal(int age) { this->age = age; } // 带参数的构造函数,用于设置年龄
int getAge() { return age; } // 获取年龄的函数
protected:
int age; // 年龄作为Animal类的数据成员
};
class Dog :public Animal // 继承自Animal类
{
public:
Dog(int a, string color) : Animal(a) { this->color = color; } // 构造函数,设置年龄和颜色
void showInfor() // 输出狗的信息
{
cout << "age:" << age << endl; // 可以直接访问Animal类中的年龄数据成员
cout << "color:" << color << endl; // 也可以访问Dog类中新增加的颜色数据成员
}
private:
string color; // 新增加的颜色数据成员
};