zoukankan      html  css  js  c++  java
  • C++类模板 template <class T>

    C++在发展的后期增加了模板(template )的功能,提供了解决这类问题的途径。可以声明一个通用的类模板,它可以有一个或多个虚拟的类型参数。

    比如:

    1. class Compare_int
    2. class Compare_float

    都是比较大小的函数,只是参数类型不同,于是用一个类模版综合成一个函数:

    template <class numtype> //声明一个模板,虚拟类型名为numtype
    class Compare //类模板名为Compare
    {
    public : 
         Compare(numtype a,numtype b){      
                x=a;y=b;   
         }   
         numtype max( ){
            return (x>y)?x:y; 
         }   
         numtype min( ){
            return (x<y)?x:y;   
         }
    private :   
        numtype x,y;
    };
    
        

    1. 用类模板定义对象时用以下形式:
        类模板名<实际类型名> 对象名;
        类模板名<实际类型名> 对象名(实参表列);
    如:
        Compare<int> cmp;
        Compare<int> cmp(3,7);

    2. 如果在类模板外定义成员函数,应写成类模板形式:
       template <class 虚拟类型参数>
       函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {…}

       template <class numtype>
        numtype Compare<numtype>::max( )
        {
            return (x>y)?x:y;
        }

    3. 类模板的类型参数可以有一个或多个,每个类型前面都必须加class,如:
        template <class T1,class T2>
        class someclass
        {…};
    在定义对象时分别代入实际的类型名,如:
        someclass<int,double> obj;

  • 相关阅读:
    phpstorm常用快捷键
    tp3.2.3运用phpexcel将excel文件导入mysql数据库
    TP3.2加载外部PHPexcel类,实现导入和导出
    Navicat常用快捷键
    thnkphp框架面试问题
    PHPSQL注入
    PHP4个载入语句的区别
    goflyway简单使用
    ubuntu16.04 HyperLedger Fabric 1.2.0 开发环境搭建
    DApp demo之pet-shop
  • 原文地址:https://www.cnblogs.com/msymm/p/9750787.html
Copyright © 2011-2022 走看看