我是靠谱客的博主 高挑玫瑰,最近开发中收集的这篇文章主要介绍C++ - 重载函数与模板函数(function template)一、重载函数二、模板函数(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 

最后

以上就是高挑玫瑰为你收集整理的C++ - 重载函数与模板函数(function template)一、重载函数二、模板函数(function template)的全部内容,希望文章能够帮你解决C++ - 重载函数与模板函数(function template)一、重载函数二、模板函数(function template)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部