C++函数模板和类模板

所谓函数化多态性,就是将程序所处理的对象的类型参数化,使得一段程序可以用于处理多种不同类型的对象。

1.函数模板

template<class T>//定义函数模板
void outputArray(const T* array,int cout){
    for(int i=0;i<cout;i++)
        cout<<array[i]<<" ";
    cout<<endl;
}

2.类模板

  使用类模板是用户可以为类定义一种模式,使得类中的默写数据成员、某些成员函数的参数、返回值或局部变量能取任意类型(包括系统定义的和用户自定义的)。

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

struct Student{  //结构体
    int id;
    float gpa;
};

template<class T>   //类模板:实现对任意类型数据进行存取
class Store{
    private:
        T item;
        boll haveValue;
    public:
        store():
        T &getElem();
        void putElem(const T &x);  
    
};

//以下实现各成员函数
template<class T>
Store<T>::store():haveValue(false){}

template<class T>
T &Store<T>:getElem(){
    if(!haveValue){
        cout<<"NO item present!"<<endl;
        exit(1);//使程序完全退出,返回到操作系统
    }
    return item;
}

template<class T>
void Store<T>::putElem(const T &x){
    haveValue=true;
    item=x;
}

 

转载于:https://www.cnblogs.com/biwangwang/p/11349443.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值