8.12C++

1.思维导图

2.

编程题:

以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:

比喻:动物园的讲解员和动物表演

想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。

在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。

具体过程如下:

定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为。

#include <iostream>

using namespace std;
class Animal
{
private:
    string name;
public:
    Animal(){}
    Animal(string name):name(name)
    {
        cout << "昵称:" << name << endl;
    }
    virtual void perform() = 0;
    virtual ~Animal()
    {
        cout << "Animal::析构函数" << endl;
    }
};

class Bear:virtual public Animal
{
private:
    string per;
    int age;
public:
    Bear(){}
    Bear(string name,int age,string per):Animal(name),per(per),age(age)
    {}
    ~Bear()
    {
        cout << "Bear::析构函数" << endl;
    }
    void perform()
    {
        cout << "年龄:" << age << endl;
        cout << "表演:" << per << endl;
    }
};

class Monkey:virtual public Animal
{
private:
    string per;
    int age;
public:
    Monkey(){}
    Monkey(string name,int age,string per):Animal(name),per(per),age(age)
    {}
    ~Monkey()
    {
        cout << "Monkey::析构函数" << endl;
    }
    void perform()
    {
        cout << "年龄:" << age << endl;
        cout << "表演:" << per << endl;
    }
};
class Tiger:virtual public Animal
{
private:
    string per;
    int age;
public:
    Tiger(){}
    Tiger(string name,int age,string per):Animal(name),per(per),age(age)
    {}
    ~Tiger()
    {
        cout << "Tiger::析构函数" << endl;
    }
    void perform()
    {
        cout << "年龄:" << age << endl;
        cout << "表演:" << per << endl;
    }
};

int main()
{
    Animal *a =new Bear("熊大",5,"上树采蜂蜜");
    a->perform();
    delete a;
    cout << "—————————————————————————" << endl;
    Animal *a1 =new Monkey("毛毛",3,"水中捞月");
    a1->perform();
    delete a1;
    cout << "—————————————————————————" << endl;
    Animal *a2 =new Tiger("泰哥",6,"撒娇卖萌");
    a2->perform();
    delete a2;
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值