c++ 多态

1、重载和多态的关系:

多态分为静态多态和动态多态:

静态多态 包含 重载和泛型编程

动态多态 ---》虚函数

 

2、重载案例:

//
// Created by luzhongshan on 10/18/19.
//
#include "stdlib.h"
#include "iostream"
using namespace std;
int Add(int left, int right)
{
    return left + right;
}
double Add(double left, int right)
{
    cout<<"sizeof a: "<< sizeof(left)<<"sizeof b:"<< sizeof(right)<<endl;
    return left + right;
}

int main()
{
    int  a=Add(10, 20);
    cout<<"a  "<<a<<endl;

    //Add(10.0, 20.0);  //这是一个问题代码
    double b =Add(10.0,20);  //正常代码
    cout<<"sizeof  b"<< sizeof(b)<<"b  "<<b<<endl;

    return 0;
}

 

3、虚函数案例:

//
// Created by luzhongshan on 10/18/19.
//
#include "iostream"
using namespace std;

class TakeBus
{
public:
    void TakeBusToSubway()
    {
        cout << "go to Subway--->please take bus of 318" << endl;
    }
    void TakeBusToStation()
    {
        cout << "go to Station--->pelase Take Bus of 306 or 915" << endl;
    }
};
//知道了去哪要做什么车可不行,我们还得知道有没有这个车
class Bus
{
public:
    virtual void TakeBusToSomewhere(TakeBus& tb) = 0;  //???为什么要等于0
};

class Subway:public Bus
{
public:
    virtual void TakeBusToSomewhere(TakeBus& tb)
    {
        tb.TakeBusToSubway();
    }
};
class Station :public Bus
{
public:
    virtual void TakeBusToSomewhere(TakeBus& tb)
    {
        tb.TakeBusToStation();
    }
};

int main()
{
    TakeBus tb;
    Bus* b = NULL;
    Bus* a = NULL;
    //假设有十辆公交车,如果是奇数就是去地铁口的,反之就是去火车站的
    b = new Subway;
    a = new Station;

    b->TakeBusToSomewhere(tb);
    a->TakeBusToSomewhere(tb);
    delete b;
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值