C++学习day6

 1.思维导图

 

 2.作业:

编程题:
以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为。
#include <iostream>

using namespace std;
class Animal
{

public:
    string name;
    int weight;
    string color;
    string sex;
public:
    Animal(){}
    Animal(string n,int w,string c,string s):name(n),weight(w),color(c),sex(s)
    {

        cout << "我是动物园的讲解员,下面由我来给大家介绍这里的东动物"<< endl;
    }
    //构造纯虚函数
    virtual void perfrom()
    {

    }
    void show()
    {
        cout << "name: "<< name<<endl;
        cout << "weight:" <<weight<< endl;
        cout << "color:"<< color<<endl;
        cout << "sex:"<< sex<<endl;
    }




};
class Lion:public Animal
{
private:
    string say;
public:
    Lion(){}
    Lion (string n ,int w,string c,string s,string a):Animal(n,w,c,s),say(a)
    {

    }

    void perfrom()
    {
        cout << "Lion:我要表演狮子怒吼" << endl;
    }
    void show()
    {
        cout << "name: "<< name<<endl;
        cout << "weight:" <<weight<< endl;
        cout << "color:"<< color<<endl;
        cout << "sex:"<< sex<<endl;
        cout << "技能:say:"<< say <<endl;
    }
};
class Elephant:public Animal
{
private:
    string water;
public:
    Elephant(){}
    Elephant(string n,int w,string c,string s,string wa):Animal(n,w,c,s),water(wa)
    {

    }
    void perfrom()
    {

        cout << "elephant:我要表演大象喷水" << endl;
    }
    void show()
    {
        cout << "name: "<< name<<endl;
        cout << "weight:" <<weight<< endl;
        cout << "color:"<< color<<endl;
        cout << "sex:"<< sex<<endl;
        cout << "技能:water:"<< water <<endl;
    }

};
class Monkey:public Animal
{
private:
    string eat;
public:
    Monkey(){}
    Monkey(string n,int w,string c,string s,string e):Animal(n,w,c,s),eat(e)
    {

    }

    void perfrom()
    {
        cout << "monkey: 我要表演猴子吃桃" << endl;
    }
    void show()
    {
        cout << "name: "<< name<<endl;
        cout << "weight:" <<weight<< endl;
        cout << "color:"<< color<<endl;
        cout << "sex:"<< sex<<endl;
        cout << "技能:eat:"<< eat <<endl;
    }
};



int main()
{
    Animal *p;
    Lion s("狮子",200,"yellow","公","表演节目:狮子怒吼");
    Elephant e("大象",20000,"blue","母","节目:大象喝水");
    Monkey m("猴子",10,"bleak","公","节目:猴子吃桃");
    s.show();

    p=&s;
    p->perfrom();
    e.show();
    p=&e;
    p->perfrom();
    m.show();
    p=&m;
    p->perfrom();
    return 0;
}

效果图:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值