关注公众号

关注公众号

手机扫码查看

手机查看

喜欢作者

打赏方式

微信支付微信支付
支付宝支付支付宝支付
×

C++之函数模板的概念和意义(一)

2020.9.28

一、函数模板的引出:

1、c++中有几种交换变量的方法:

(1)定义宏代码块

(2)定义函数

代码版本一:

#include <iostream>
#include <string>
using namespace std;
#define SWAP(t,a,b)  
do                    
{                    
    t c =a;          
    a =b;            
    b = c;          
}while(0)
int main()

    int a =2;
    int b =5;
    SWAP(int , a , b );
    cout<<"a= "<<a<<endl;
    cout<<"b= "<<b<<endl;
    double m =4;
    double n =6;
    cout<<"m = "<<m<<endl;
    cout<<"n= "<<n<<endl;
    return 0;

输出结果:

root@txp-virtual-machine:/home/txp# ./a.out
a= 5
b= 2
m = 4
n= 6

注解:我们看两个数值交换成功。

我们再用使用函数的方式来实现这个功能,当然以前我们在c语言里面使用指针传参方式来实现这种两个数值直接的交换,现在我们利用c++里面更加高级的方式来实现,就是使用引用来实现(不过它的本质还是指针来实现,只是我们只用引用再不用去考虑指针的细节了)

代码版本二:

#include <iostream>
#include <string>
using namespace std;
void Swap(int& a , int& b )//const int * a ,const int * b '

   int c =a;
   a=b;
   b=c;

void Swap(double& a,double& b)

   double c =a;
   a=b;
   b=c;

void Swap( string& a, string& b)

   string c =a;
   a=b;
   b=c;

int main()

 int a =2;
 int b =5;
 Swap(a,b);
 cout<<"a= "<<a<<endl;
 cout<<"b= "<<b<<endl;
 double m =4;
 double n =6;
 cout<<"m= "<<m<<endl;
 cout<<"n= "<<n<<endl;
 string d = "Txp";
 string t = "xiaoping";
 cout<<"d= "<<d<<endl;
 cout<<"t= "<<t<<endl;
 return 0;


推荐
关闭