C++ 多态、重载、模板 的区别与联系

直接用简洁的代码进行了示例对比,以清晰直观展示三者的区别和联系:

//多态、重载、模板  的区别联系   ok


#include <iostream>
using namespace std;

//
//【1】多态
class Shape
{
public:
    // Shape 类中的虚函数 draw()
    virtual void draw(){cout << "虚函数 - Drawing shape" << endl;}
};
class Circle : public Shape
{
public:
    // Circle 类中重新实现 Shape 中的虚函数 draw()
    void draw() { cout << "多态1 - Drawing a circle" << endl; }
};
class Rectangle : public Shape
{
public:
    // Rectangle 类中重新实现 Shape 中的虚函数 draw()
    void draw() { cout << "多态2 - Drawing a rectangle" << endl; }
};

// 
//【2】函数重载,重载 draw() 函数
void draw(int i) { cout << "重载1  Drawing integer: " << i; printf(" %d\n", i+1); }
void draw(double d) { cout << "重载2  Drawing double: " << d << endl; }

//
//【3】函数模板
template<class T>
void draw(T num) { cout << "函数模板  The value is " << num << endl; }

int main()
{
    // 【1】多态性
    Shape* s;
    Circle c;
    Rectangle r;
    s = &c;
    s->draw(); // 调用 Circle 类中的 draw() 函数
    s = &r;
    s->draw(); // 调用 Rectangle 类中的 draw() 函数

    // 【2】函数重载
    draw(10);
    draw(1.234);

    //【3】函数模板
    draw(666);//参数类型和重载的一样,用了重载。所以不该这么用。
    draw(6.66);
    draw("678");//参数类型和重载的不同,选择了模板。
    draw(true);

    return 0;
}

示例代码输出:

多态1 - Drawing a circle

多态2 - Drawing a rectangle

重载1  Drawing integer: 10 11

重载2  Drawing double: 1.234

重载1  Drawing integer: 666 667  #这里调了重载

重载2  Drawing double: 6.66       #这里调了重载

函数模板  The value is 678

函数模板  The value is 1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值