您的位置:首页 > 编程语言 > C语言/C++

c++ 模版的使用方法

2013-04-26 13:51 302 查看
     我们在编写c++程序的时候可能需要自己的编写函数模版和类模板,模版的好处我就不多说了,下面我就模版的语法做一下说明,并写一个例子

    一、函数模版的写法

   函数模板的一般形式如下:

    Template<class 或者typename T>
     返回类型 函数名(形参表)

     {//函数定义体 }
       note:template是一个声明模板的关键字,表示声明一个模板关键字class不能省略,如果类型形参多余一个 ,每个形参前都要加class <类型 形参表>可以包含基本数据类型可以包含类类型.
下面是程序示列:

#include<iostream>
using std::cout;
using std::endl;
template<typename T>
T Min(T x, T y)
{
cout<<"The value of x is "<<x<<endl;
cout<<"The value of y is "<<y<<endl;
if(x>y)
return y;
return x;
}
int main()
{
int n1=6,n2=5;
double b1=4.56,b2=5.46;
cout<<"The int type, the min value is "<<Min(n1,n2)<<endl;
cout<<"The double type, the min value is "<<Min(b1,b2)<<endl;
return 0;
}

 二、类模版

    定义一个类模板:

Template < class或者也可以用typename T > class类名{ //类定义...... };

note:其中,template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。

  下面是程序示例:

   myclass.h文件

  
#ifndef MYCLASS_H
#define MYCLASS_H
#include <iostream>
using namespace std;
template<typename T1,typename T2>
class myClass
{
public:
myClass();
private:
T1 number1;
T2 number2;
public:
myClass(T1 a,T2 b);
void show();
};

template<typename T1,typename T2>

myClass<T1,T2>::myClass(T1 a, T2 b):number1(a),number2(b)
{}

void show();
template<typename T1,typename T2>
void myClass<T1,T2>::show()
{
cout<<"I="<<number1<<",J="<<number2<<endl;
}

template<typename T1,typename T2>
myClass<T1,T2>::myClass()
{
cout<<"this is the default constructor"<<endl;
}

#endif // MYCLASS_H
  

[b]   //main.cpp文件[/b]
#include <iostream>
#include<string>
#include"myclass.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
myClass<int,int> class1(3,5);
class1.show();

myClass<int ,char>classChar(3,'5');
classChar.show();

myClass<int,string>classString(4,"luomingzhong");
classString.show();
return 0;
}


可能有同学会问为什么模版的写法,定义与声明放在同一个文件中,而不是像类的定义一样,声明放在头文件中,而定义放在.cpp中?本人不想做过多解释,下面的链接较详细的说明了c++模版的定义为什么放在一起。

 
链接一

为什么模版的定义和声明要放在一起

   链接二

模版的特化

   以供参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 模版