[C++/PTA] 狗的继承

[C++/PTA] 狗的继承

题目要求

完成两个类,一个类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

解题思路

定义两个构造函数,一个默认构造函数和一个带参数的构造函数,以及一个获取年龄的成员函数getAge。
在Dog类中,定义了一个构造函数,用于设置年龄和颜色,并新增加了一个成员函数showInfor,用于输出狗的信息。

代码

#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; // 新增加的颜色数据成员
};

总结

该题考察构造函数相关知识,读者可躬身实践。
我是秋说,我们下次见。

posted @ 2023-05-30 18:17  秋说  阅读(131)  评论(0编辑  收藏  举报  来源