c++ day 6

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

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

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

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

具体过程如下:

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

#include <iostream>
using namespace std;
class Animal
{
public:
    virtual void perform() = 0;//纯虚函数

};
class Tiger:public Animal
{
private:
    string foods;
    string feature;
public:
    Tiger(){}
    Tiger(string foods,string feature):foods(foods),feature(feature)
    {}
    void perform()//函数重写
    {
        cout << "老虎的狩猎: " << foods << "    " << "老虎喜欢做: " << feature << endl;
    }
};
class Monkey:public Animal
{
private:
    string foods;
    string feature;
public:
    Monkey(){}
    Monkey(string foods,string feature):foods(foods),feature(feature)
    {}
    void perform()//函数重写
    {
        cout << "猴子喜欢吃的食物是: " << foods << "    " << "猴子喜欢做: " << feature << endl;
    }
};
int main()
{
    Tiger l("野狗","睡觉");
    Monkey m("仙桃","爬黄山");
    Animal *interpreter;
    interpreter = &l;
    interpreter->perform();//父类的指针或者引用,可以指向或者初始化子类的对象,调用子类对父类重写的函数,进而展开子类的功能
    interpreter = &m;
    interpreter->perform();//父类的指针或者引用,可以指向或者初始化子类的对象,调用子类对父类重写的函数,进而展开子类的功能
    return 0;
}

相关推荐

  1. MSc CDA Take-Home

    2023-12-06 13:52:05       60 阅读
  2. CDA一级备考策略分享

    2023-12-06 13:52:05       32 阅读
  3. CDA-LevelⅡ【考题整理-带答案】

    2023-12-06 13:52:05       50 阅读
  4. Spring Data访问Elasticsearch----CDI集成

    2023-12-06 13:52:05       36 阅读
  5. CDA Level Ⅰ 2023认证考试大纲

    2023-12-06 13:52:05       78 阅读
  6. web server apache tomcat11-33-CDI

    2023-12-06 13:52:05       33 阅读
  7. Spring Data访问 MongoDB(十六)----CDI集成

    2023-12-06 13:52:05       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 13:52:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 13:52:05       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 13:52:05       82 阅读
  4. Python语言-面向对象

    2023-12-06 13:52:05       91 阅读

热门阅读

  1. [cmake] ---- set_property

    2023-12-06 13:52:05       52 阅读
  2. 从零开始的C++(二十)

    2023-12-06 13:52:05       60 阅读
  3. 小白理解GPT的“微调“(fine-tuning)

    2023-12-06 13:52:05       68 阅读
  4. Go语言基础面经

    2023-12-06 13:52:05       55 阅读
  5. 【C++】初阶模板

    2023-12-06 13:52:05       60 阅读
  6. 技术难题:解密编程中的挑战与突破

    2023-12-06 13:52:05       56 阅读
  7. 设计模式系列文章

    2023-12-06 13:52:05       69 阅读
  8. lua_next

    2023-12-06 13:52:05       61 阅读
  9. vscode console.log快捷键

    2023-12-06 13:52:05       56 阅读