zoukankan      html  css  js  c++  java
  • c++函数模板

    函数模板存在的意义;如果同一函数,参数类型有所不同,相同的功能可能会定义多个函数实例,这十分繁冗

    #include<iostream>
    using namespace std;
    void swap(int &a,int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
    
    void swap(char &a, char &b)
    {
        char temp = a;
        a = b;
        b = temp;
    }
    
    void main()
    {
        int a = 8,b=10;
        swap(a,b);
        cout << "a----" << a << "b---" <<b << endl;
        char *x = "陈培昌";
        char *y = "付高峰";
        swap(x,y);
        cout << "x----" << x << "y---" << y << endl;
        system("pause");
    }

    输出结果

    • 定义函数模板
    #include<iostream>
    using namespace std;
    
    
    template <typename T>
    void myswap(T &a,T &b)
    {
        T c;
        c = a;
        a = b;
        b = c;
    }
    
    void main()
    {
        int a = 8;
        int b = 10;
        myswap<int>(a,b);
        cout << "a----" << a << "b---" <<b << endl;
        char *x = "陈培昌";
        char *y = "付高峰";
        //cout << "x----" << x << "y---" << y << endl;
        myswap<char*>(x, y);
        cout << "x----" << x << "y---" << y << endl;
        system("pause");
    }

    输出结果:

  • 相关阅读:
    Oracle三大设计范式
    数据库查询4
    Oracle 常用内置函数
    数据库查询2
    数据库查询练习1
    Oracle 建表
    线程1—Runnable
    线程1—Thread
    输入输出2
    输入输出1
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12045115.html
Copyright © 2011-2022 走看看