• C++(四十二) — 函数模板多态


     1、函数模板(参数多态)

      相当于一个函数发生器,参数多态,可以重载。

      普通函数和模板函数的本质区别

    1. 普通函数的调用,可以进行隐式的类型转换;
    2. 函数模板的调用,使用类型参数化,严格按照类型进行匹配,不会进行类型的自动转换;

       一个函数模板可以取代许多具体的函数定义,可以大大减少编程工作量。

    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    template <typename P> //函数模板
    void ArrayInput(P array, int num)
    {
        cout << "输入" << num << "" << typeid(P).name()
            << "" << "型数据" << endl;
        for (int j = 0; j < num; j++)
            cin >> array[j];
    }
    void main()
    {
        int number;
        float floatArray[4];
        int intArray[3];
        number = sizeof(floatArray) / sizeof(float);
        ArrayInput(floatArray, number);
        number = sizeof(intArray) / sizeof(int);
        ArrayInput(intArray, number);
        system("pause");
    }

    2、类模板

       使用类模板来定义栈类,进栈、出栈。

    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    template <class T,int i> //函数模板
    class MyStack
    {
    private:
        //栈空间:Buffer[0]~Buffer[i-1],Buffer[i]表示栈底
        T Buffer[i + 1];
        int size;
        int top;
    public:
        MyStack(T zero)
        {
            size = i;
            top = i;
            for (int j = 0; j <= i; j++)  //初始化缓冲区
            {
                Buffer[j] = zero;
            }
        }
        void push(const T item);
        T pop();
    };
    
    template <class T,int i>  // 模板类成员函数的定义
    void MyStack<T, i>::push(const T item)
    {
        if (top > 0)
            Buffer[--top] = item;
        else
            cout << "栈溢出" << endl;
    }
    
    template <class T,int i>
    T MyStack<T, i>::pop()
    {
        T temp;
        if (top < size)
            temp = Buffer[top++];
        else
        {
            temp = Buffer[top];
            cout << "栈已空" << endl;
        }
        return temp;
    }
    
    void main()
    {
        MyStack<int, 5> S1(0);
        S1.push(4);
        cout << S1.pop() << endl;
        MyStack<char*, 5> S2("empty");
        S2.push("china");
        cout << S2.pop() << endl;
        cout << S2.pop() << endl;
        system("pause");
    }
  • 相关阅读:
    springboot之热部署
    在动态sql的使用where时,if标签判断中,如果实体类中的某一个属性是String类型,那么就可以这样来判断连接语句:
    对集合进行判空的操作
    配置logback日志管理的时候
    SpringBoot序列化时间类型的问题
    Cannot determine embedded database driver class for database type NONE
    idea的基础设置
    使用navicat创建数据库
    LESS
    数据库链接池--简单的理解
  • 原文地址:https://www.cnblogs.com/eilearn/p/10962172.html
Copyright © 2020-2023  润新知