c++继承多态虚函数例题

  1. 写一个抽象类Pet,里面有3个纯虚函数void setName(string name),string getName();void play();
  2. 写一个类Animal,里面有保护类型的成员变量string name,一个带参数的构造函数,2个成员函数,void walk),void eat()
  3. 写一个类Cat,要求同时继承题2,3中的类。
  4. 写一个类Dog,要求同时继承2,3中的类。
    自己设计编写代码,生成Cat,Dog对象,并且要求体现出多态。
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
    virtual void setName(string name) = 0;
    virtual string getName() = 0;
    virtual void play()=0;
};
class Animal {
protected:
    string name;
public:
    Animal(string n) :name(n) {}
    void walk() {};
    void eat(){};
};
class Cat :public Pet, Animal {
public:
    Cat() :Animal("Cat") {}
    void setName(string name) {
        name = name;
    }
    string getName(){
        return name;
    }
    void walk() {
        cout << getName() << " is walking" << endl;
    }
    void eat() {
        cout << getName() << " is eating" << endl;
    }
    void play() {
        cout << getName() << " is playing" << endl;
    }
};
class Dog :public Pet, Animal{
public:
    Dog() :Animal("Dog") {}
    void setName(string name) {
        name = name;
    }
    string getName() {
        return name;
    }
    void walk() {
        cout << getName() << " is walking" << endl;
    }
    void eat() {
        cout << getName() << " is eating" << endl;
    }
    void play() {
        cout << getName() << " is playing" << endl;
    }
};
int main()
{
    Dog d;
    Cat c;
    d.walk();
    c.walk();
    d.eat();
    c.eat();
    d.play();
    c.play();
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清欢_小铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值