C++:函数模板和类模板

函数模板类似于函数重载。

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

template<类型形式参数表> //模板前缀

返回类型  函数名(形式参数表)

{

//函数体

}

程序如下:

#include<iostream.h>

template<class T>   //T代表某种数据类型,也可以用template<typename T> 

void swap(T &x1, T &x2)

{

    T temp;

    temp = x1; x1 = x2; x2 = temp;

}

void main()

{

    char c1 = 'a', c2 = 'b';

    int i1 = 10, i2 = 20;

    swap(c1, c2);

    swap(i1, i2);

}

C++ 中类模板的写法如下:

template <类型参数表>
class 类模板名{
    成员函数和成员变量
};

类型参数表的写法如下:

class类塑参数1, class类型参数2, ...

类模板中的成员函数放到类模板定义外面写时的语法如下:

template <类型参数表>
返回值类型  类模板名<类型参数名列表>::成员函数名(参数表)
{
    ...
}

用类模板定义对象的写法如下:

类模板名<真实类型参数表> 对象名(构造函数实际参数表);

如果类模板有无参构造函数,那么也可以使用如下写法:

类模板名 <真实类型参数表> 对象名;

类模板看上去很像一个类。下面以 Pair 类模板为例来说明类模板的写法和用法。

#include <iostream>
#include <string>
using namespace std;

template <class T1,class T2>

class Pair
{
public:
    Pair(T1 k,T2 v):key(k),value(v) { };
    bool operator < (const Pair<T1,T2> & p) const;
	
	T1 getKey(void) const;
	T2 getValue(void) const;

private:
    T1 key;    //关键字
    T2 value;  //值
};

template<class T1,class T2> //每个函数前面都应该声明
bool Pair<T1,T2>::operator < (const Pair<T1,T2> & p) const //Pair的成员函数 operator < 
{ 
    return value < p.value;  //"小"的意思就是值小
}

template<class T1,class T2> //每个函数前面都应该声明
T1 Pair<T1,T2>::getKey(void) const
{ 
    return key;
}

template<class T1,class T2> //每个函数前面都应该声明
T2 Pair<T1,T2>::getValue(void) const
{ 
    return value;
}
#include "template.h"

using namespace std;

int main()
{
    Pair<string,int> Tom("Tom", 19); //实例化出一个类 Pair<string,int>
    cout << Tom.getKey() << " " << Tom.getValue() << endl;

	Pair<string,int> Ally("Ally", 20);
	cout << Ally.getKey() << " " << Ally.getValue()  << endl;

	if(Tom < Ally)
	{
		cout << "Tom is younger than Ally" << endl;
	}
	else
	{
		cout << "Ally is younger than Tom" << endl;
	}

    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AllenSun-1990

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值