zoukankan      html  css  js  c++  java
  • C++函数模板的使用

    函数模板可以用来创建一个通用的函数,以支持多种不同形参,避免重载函数的函数体重复设计。它的最大的特点就是吧函数实用的数据类型作为参数。

    定义函数模板的一般形式为:

    template<typename T>

    或者

    template<class T>

    1下面我们来试着用函数重载来定义不同类型的函数

    int:

    int int_add(int a,intb)

    {

    int c;

    c = a + b;

    return c;

    }

    double:

    double double_add(double a;double b)

    {

    double c;

    c = a + b;

    return c;

    }

    int main()

    {

    cout<<int_add(5,3)<<endl;    //调用int_add函数

    cout<<double(5.1,3.1)<<endl;   //调用double_add函数

    return 0;

    }

    2同样我们可以使用构造函数完成相同的操作

    #include<iostream>
    using namespace std;
    int n_add(int a,int b) //定义函数n_add用于int型数据相加
    {
    int c;
    c=a+b;
    return c;
    }
    double n_add(double a,double b) //定义函数n_add用于double型函数相加
    {
    double c;
    c=a+b;
    return c;
    }
    int main()
    {
    cout<<n_add(5,3)<<endl; //调用n_add函数
    cout<<n_add(5.35,5.5)<<endl; //调用n_add函数
    return 0;
    }

    3使用函数模板

    #include<iostream>

    using namespace std;

    template<typename T>

    T n_add(T a,T b)

    {

    T c;

    c = a + b;

    return c;

    }

    int main()

    {

    cout<<n_add(5,3)<<endl;

    cout<<n_add(5.1,3.1)<<endl;

    return 0;

    }

  • 相关阅读:
    在rhel6上安装Python 2.7和Python 3.3
    RHEL7 -- Linux搭建FTP虚拟用户
    RHCE7 -- IPv6
    RHEL7 -- nmcli的使用
    设置Adobe Reader打开PDF文件保持记忆功能
    iptalbes -F
    服务器IP地址后修改SQL Server配置
    配置SELINUX
    11G新特性 -- 分区表和增量统计信息
    11G新特性 -- Statistics Preferences
  • 原文地址:https://www.cnblogs.com/DannyShi/p/4582225.html
Copyright © 2011-2022 走看看