C++ - 重载函数与模板函数(function template)

参考:

  1. CSDN - 【C++】C++中函数重载的理解
  2. 《Essential C++》

一、重载函数

1.1 重载函数的意义

重载函数通常用来在同一个作用域内用同一个函数名命名一组功能相似的函数,这样做减少了函数名的数量,避免了名字空间的污染,对于程序的可读性有很大的好处。
每个重载函数的参数列表必须和其他重载函数不同。

1.2 使用场景

#include <iostream>
using namespace std;

int Add(int a, int b) {
    return a+b;
}
double Add(double a, double b) {
    return a+b;
}
string Add(string a, string b) {
    return a+b;
}

int main() {
    cout << Add(1, 2) << endl;
    cout << Add(1.1, 2.2) << endl;
    cout << Add("1", "2") << endl;
    return 0;
}

输出结果:

3
3.3
12

1.3 重载函数的原理

在C++中,虽然重载函数的函数名一样,但其在符号表中生成的名称并不相同。
重载函数是一种静态多态(编译时多态)。

二、模板函数(function template)

function template 将参数列表中指定的全部(或部分)参数的类型信息抽离了出来。

#include <iostream>
#include <vector>
using namespace std;

//这些标识符扮演者占位符的角色,用来放置函数参数列表以及函数体内的某些实际数据类型。
template <typename elemType>
void Function(const string &str, const vector<elemType> &vec)
{
    cout << str << endl;
    for (int i = 0; i < vec.size(); ++i)
    {
        elemType temp = vec[i];
        cout << temp << " ";
    }
    cout << endl;
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]));
    Function("Some Numbers:", vec);
    return 0;
}

输出结果:

Some Numbers:
1 2 3 4 5 6 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值