四个C++函数模板实例
生活随笔
收集整理的這篇文章主要介紹了
四个C++函数模板实例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
實(shí)例一
#include <string> #include <iostream> using namespace std; template<typename T> void print(const T& var) { cout << var << endl; } int main() { string str("Hello World"); const int num=12345; print(str); print(num); return 0; }
實(shí)例二
#include <iostream.h> // 定義函數(shù)模板,找出三個(gè)值中最小的值,與數(shù)據(jù)類型無(wú)關(guān) template <class T> T min(T ii, T jj, T kk) { T temp; if((ii<jj)&&(ii<kk)){ temp=ii; } else if((jj<ii)&&(jj<kk)){ temp=jj; } else{ temp=kk;} return temp; } int main() { cout<<min("anderson","Washington","Smith")<<endl; return 0; }
實(shí)例三
#include <iostream> #include <string>using namespace std;template<class T> void swap(T *x, T *y){//函數(shù)的模板,只要能使用等號(hào)賦值類型都可以用這個(gè)模板互換T temp = *x;*x = *y;*y = temp;}int main() {int i = 9, j = 5;float k = 9.2, l = 5.6;swap(&i, &j);//交換整形swap(&k, &l);//交換浮點(diǎn)型cout<<"i = "<<i<<" , j = "<<j<<endl;cout<<"k = "<<k<<" , l = "<<l<<endl;return 0; }
實(shí)例四
使用普通函數(shù);
#include<iostream>using namespace std;int int_add(int a,int b)//定義函數(shù)int_add用于int型數(shù)據(jù)相加 {int c;c=a+b;return c; } double dou_add(double a,double b)//定義函數(shù)dou_add用于double型函數(shù)相加 {double c;c=a+b;return c; }int main() {cout<<int_add(5,3)<<endl; //調(diào)用int_add函數(shù)cout<<dou_add(5.35,5.5)<<endl; //調(diào)用dou_add函數(shù)return 0; }使用函數(shù)重載; #include<iostream>using namespace std;int n_add(int a,int b)//定義函數(shù)n_add用于int型數(shù)據(jù)相加 {int c;c=a+b;return c; } double n_add(double a,double b)//定義函數(shù)n_add用于double型函數(shù)相加 {double c;c=a+b;return c; }int main() {cout<<n_add(5,3)<<endl; //調(diào)用n_add函數(shù)cout<<n_add(5.35,5.5)<<endl; //調(diào)用n_add函數(shù)return 0; }
使用函數(shù)模板
#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.35,5.5)<<endl;return 0; }
總結(jié)
以上是生活随笔為你收集整理的四个C++函数模板实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: arcgis 卸载和注册表相关总结
- 下一篇: C++ string源码