如何将C++函数模板和类模板巧妙地结合成一个长尾?

2026-04-16 19:524阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计407个文字,预计阅读时间需要2分钟。

如何将C++函数模板和类模板巧妙地结合成一个长尾?

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

1. 函数模板:template class T // 定义函数模板 void outputArray(const T *array, int count); // 输出数组元素

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

1.函数模板

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

2.类模板

如何将C++函数模板和类模板巧妙地结合成一个长尾?

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

#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; }

本文共计407个文字,预计阅读时间需要2分钟。

如何将C++函数模板和类模板巧妙地结合成一个长尾?

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

1. 函数模板:template class T // 定义函数模板 void outputArray(const T *array, int count); // 输出数组元素

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

1.函数模板

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

2.类模板

如何将C++函数模板和类模板巧妙地结合成一个长尾?

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

#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; }