c++第六天

1.定义一个animal基类,其中有perform虚函数,用于在子类中实现不同的表演行为

#include <iostream>

using namespace std;

//定义一个动物 基类
class Animal
{
private:
    string name;
public:
    //无参函数
    Animal(){}
    //有参函数
    Animal(string n):name(n)
    {}
    virtual void perform()
    {
        cout << "动物园里有什么" << endl;
    }
};

//定义一个 狮子类 继承于动物类
class Lion:public Animal
{
private:
    int high;
public:
    //无参构造
    Lion(){}
    //有参构造
    Lion(string n,int h):Animal(n),high(h)
    {}
    void perform()
    {
        cout << "狮子表演跳舞" << endl;
    }
};

//定义一个 大象类  继承于动物类
class Elephant:public Animal
{
private:
    int weight;
public:
    //无参构造
    Elephant(){}
    //有参构造
    Elephant(string n,int w):Animal(n),weight(w)
    {}
    void perform()
    {
        cout << "大象表演喝水" << endl;
    }
};

//定义一个 猴子类 继承于动物类
class Monkey:public Animal
{
private:
    string sex;
public:
    //无参函数
    Monkey(){}
    //有参构造
    Monkey(string n,string s):Animal(n),sex(s)
    {}
    void perform()
    {
        cout << "猴子表演跳绳" << endl;
    }
};
int main()
{
    cout << "大家一起来看表演" << endl;
    Lion l("狮子",200);
    Animal *p;
    p = &l;
    p->perform();

    Elephant e("大象",1000);
    p = &e;
    p->perform();

    Monkey m("猴子","雌性");
    p = &m;
    p->perform();

    return 0;
}

 

2.用函数模板实现不同类型数据的交换功能

#include <iostream>

using namespace std;

template <typename T,typename B>
void fun(T &a,B &b)
{
    B temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a = 10;
    char b = 'a';
    cout << a << " " << b << endl;
    fun(a,b);
    cout << (char)a << " " << (int)b << endl;


    return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值