zoukankan      html  css  js  c++  java
  • C++基础学习--模板机制

    C++模板机制

    C++的模板机制分为函数模板和类模板,类似于类与实例,类是一个抽象的概念,实例是具体的概念,对于模板来说类模板是抽象概念,类是具体概念;函数模板类似

    函数模板

    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    #include <pthread.h>
    #include <unistd.h>
    #include <vector>
    #include <queue>
    #include "main.h"
    using namespace std;
    
    template <typename type>
    
    void test(type &a, type &b)
    {
        type c;
        c = a;
        a = b;
        b = c;
    }
    int main()
    {
        // 利用函数模板实现获取最大值
        int a = 12;
        int b = 34;
        test(a, b);
        printf("a = %d, b = %d
    ", a, b);
        return 0;
    }
    

    类模板

    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    #include <pthread.h>
    #include <unistd.h>
    #include <vector>
    #include <queue>
    #include "main.h"
    using namespace std;
    
    template<class numType>
    class Compare {
    public:
        Compare() = default;
        Compare(numType arg):age(arg){};
        ~Compare() = default;
        void display()
        {
            printf("this is %d
    ", age);
        }
    private:
        numType age;
        numType high;
    };
    
    int main()
    {
        // 利用函数模板实现一个实体类
        Compare<int>cmp1(10);
        cmp1.display();
        Compare<char>cmp2('a');
        cmp2.display();
        return 0;
    }
    
  • 相关阅读:
    Word Ladder
    Word Ladder II
    Valid Palindrome
    java 正则表达式-忽略大小写与多行匹配
    Vue自定义指令
    定义格式化时间的全局过滤器
    Vue过滤器的使用
    daterangepicker 设置默认值为空(转载)
    js时间戳与日期格式之间的互转
    Vuedevtools安装
  • 原文地址:https://www.cnblogs.com/wangdongfang/p/14541095.html
Copyright © 2011-2022 走看看