c++函數模板1

來源:互聯網
上載者:User

標籤:pen   include   cin   get   ace   class   template   使用   沒有   

1 定義:

  函數模板 只適用於參數個數相同但是類型不同 而且函數體相同的情況

2 這個例子沒有使用模板的情況

#include <iostream>using namespace std;void Swap(int &a, int &b){    int t = a;    a = b;    b = t;}void Swap(double &a, double &b){    double t = a;    a = b;    b = t;}int main1(){    //long a = 2;    //long b = 3;    //Swap(a, b);這樣不行    int a = 2;    int b = 3;    Swap(a, b);//但是變成double以後不行 為了通用引入模板    cout << a << b << endl;    cin.get();    return 1;}

 

3 使用模板以後

 1 #include <iostream> 2 #include <string> 3 using namespace std; 4  5 /* 6 函數模板 只適用於參數個數相同但是類型不同 而且函數 7 體相同的情況 否則不可以 8 */ 9 template <typename T>//這裡typename可以變化為class10 void Swap(T &a, T &b)11 {12     T t = a;13     a = b;14     b = t;15 }16 17 int main2()18 {19     int a = 10;20     int b = 20;21     Swap(a, b);22     cout << a << b << endl;23 24     long c = 10;25     long d = 20;26     Swap(c, d);27     cout << c << d << endl;28 29     string sa = "hello";30     string sb = "zzong";31     Swap(sa, sb);32     cout << sa << sb << endl;33     34     cin.get();35     return 1;36 }

----------------------->

 

c++函數模板1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.