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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++函数模板和类模板

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300916

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午9:48
下一篇 2023年2月15日 下午9:49

相关推荐