函数模版与类模版template

函数模版

功能相同,类型不同

templeate<模版参数表>
类型名 函数名(参数表)
{
   函数的定义
}
#include <iostream>

using namespace std;

template <typename myT> 
myT mymin(myT a, myT b)
{
    return a < b ? a : b;
}

int main()
{
    int a = 2,b = 3;
    cout << mymin(a, b);

}
类模版
template<模板参数表>
class 类名
{
    类成员声明
}
//类成员声明的方法与普通类的定义相同,若要在类模版外定义其成员函数,需采用以下方式:
template<模版参数表>
类型名 类名<模板参数标识符列表>::函数名(参数表)
//使用模板类来建立对象时,应按如下形式声明:
模板名<模板参数标识符列表>对象名1...,对象名n;
#include <iostream>

using namespace std;

template <class myT> //类模版,实现对任意类型的数据进行存储
class  myArray
{
private:
    myT* items;
    int size;
public:
    myArray(myT arr[], int s);  //构造函数
    void print();
};

template<typename myT>
myArray<myT>::myArray(myT arr[],int s)
{
    items = new myT[s];
    size = s;
    for (int i = 0; i < s; i++)
        items[i] = arr[i];
}

template<typename myT>//类模版外定义成员函数
void myArray<myT>::print()
{
    for (int i = 0; i < size; i++)
        cout << " " << items[i];
}

int main()
{
    int a[]= { 1,2, 3, 4, 5 };
    char b[] = { 'a', 'b', 'c', 'd' };
    myArray<int> intArr(a, 5);
    intArr.print();
    cout << endl;
    myArray<char> charArr(b, 4);
    charArr.print();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值