直接用简洁的代码进行了示例对比,以清晰直观展示三者的区别和联系:
//多态、重载、模板 的区别联系 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