zoukankan      html  css  js  c++  java
  • 函数模板和类模板

    一、函数模板

    函数模板代表一类相同结构的函数,通过用户提供的具体参数,C++编译器在编译时刻能够将函数模板实例化,根据同一个模板创建出不同的具体函数,这些函数之间的不同之处主要在于函数内部一些数据类型的不同。

     1 #include "stdafx.h"
     2 #include <iostream>
     3 using namespace std;
     4 
     5 template <typename T>
     6 T max1(T a,T b)
     7 {
     8     return a>b ? a:b;
     9 }
    10 
    11 int main(int argc,char* argv[])
    12 {
    13     cout<<max1(1,2)<<endl;                //隐式调用int类型的max1()函数
    14     cout<<max1(5.6f,3.1f)<<endl;        //隐式调用float类型的max1()函数
    15     cout<<max1(3.14l,5.13l)<<endl;        //隐式调用double类型的max1()函数
    16     cout<<max1('A','C')<<endl;            //隐式调用char类型的max1()函数
    17     cout<<max1<int>(3,5.7f)<<endl;        //必须指定int类型
    18     system("pause");
    19     return 0;
    20 }

    执行结果:

    分析:值得注意的是代码第17行,由于第一个参数3是int型,而第二个参数5.7是float型,此时如果不指定使用什么类型,会产生编译的模糊性,即编译器不知道需要调用int类型还是float类型的max1函数。

    二、类模板

    类模板就是为类声明一种模板,使得类中的某些数据成员,或某些成员函数的参数,又或者是某些成员函数的返回值可以取任意的数据类型,包括基本数据类型和自定义数据类型。

     1 #include "stdafx.h"
     2 #include <iostream>
     3 using namespace std;
     4 
     5 struct Student
     6 {
     7     int id;
     8     float average;
     9 };
    10 
    11 //类模板
    12 template <class T>
    13 class Store
    14 {
    15 public:
    16     Store(void);        //默认构造函数
    17     T GetElem(void);    //获取
    18     void PutElem(T x);    //设定
    19 private:
    20     T item;
    21     int haveValue;
    22 };
    23 
    24 //成员函数实现,类模板的成员函数都是函数模板
    25 template <class T>
    26 Store<T>::Store(void):haveValue(0)
    27 {
    28 }
    29 
    30 template <class T>
    31 T Store<T>::GetElem(void)
    32 {
    33     if(haveValue == 0)
    34     {
    35         cout<<"item没有存入数据!"<<endl;
    36         exit(1);
    37     }
    38     return item;
    39 }
    40 
    41 template <class T>
    42 void Store<T>::PutElem(T x)
    43 {
    44     haveValue = 1;
    45     item = x;
    46 }
    47 
    48 int main(int argc, char* argv[])
    49 {
    50     Student g = {103,93.8};
    51     Store<int> S1,S2;    //声明两个Store类对象,数据成员item为int型
    52     Store<Student> S3;    //声明Store类对象,数据成员item为Student结构体类型
    53     S1.PutElem(7);
    54     S2.PutElem(-8);
    55     S3.PutElem(g);
    56     cout<<S1.GetElem()<<endl;
    57     cout<<S2.GetElem()<<endl;
    58     cout<<"ID is "<<S3.GetElem().id<<endl;
    59     cout<<"Average is "<<S3.GetElem().average<<endl;
    60     system("pause");
    61     return 0;
    62 }

    以上这个例子比较简单直观地描述了类模板的定义及使用。

    执行结果为:

  • 相关阅读:
    django restful framework 有哪些功能(10条)
    Restful 规范
    eclipse编辑环境下导入springmvc的源码
    java.lang.NoSuchMethodException: .<init>()
    spring项目出现无法加载主类
    元素 "context:component-scan" 的前缀 "context" 未绑定。
    BeanPostProcessor出现init方法无法被调用Invocation of init method failed
    spring学习笔记
    springmvc学习笔记
    打印圈1圈2
  • 原文地址:https://www.cnblogs.com/may1016/p/5073584.html
Copyright © 2011-2022 走看看