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

    模板技术:本质:把类型作参数

    模板函数:

    template <typename T1,typename T2>  //还能用class代替typename
    T1 add(T1 num1,T2 num2)  //这是一个模板函数
    {
        cout<<"T1 add(T1 num1,T2 num2)"<<endl;
        return num1 + num2;
    }
    
    int main()
    {
        int a=1,b=2;
        float f1=3.2f,f2=4.9f;
        int res = add(a,f1);
        float res2 = add(f2,b);
        cout<<res<<endl<<res2<<endl;
    }        

    模板类:

    template <typename T1,typename T2>
    class Student
    {
    public:
        Student()
        {
            cout << "Student()" << endl;
            this->name = " ";
            this->age = 0;
        }
    
        Student(const T1 &name,const T2 &age);
        void showStu()const;
    
    private:
        T1 name;
        T2 age;
    };
    
    template <typename T1,typename T2>
    Student<T1,T2>::Student(const T1 &name,const T2 &age)
    {
        cout<<"Student::Student(const T1 &name,const T2 &age)"<<endl;
        this->name = name;
        this->age = age;
    }
    
    template <typename T1,typename T2>
    void Student<T1,T2>::showStu()const
    {
        cout<<"void Student::showStu()const"<<endl;
        cout<<this->name<<" "<<this->age<<endl;;
    }
    
    int main()
    {
        Student<string ,int> stu("zhangsan",22);
        stu.showStu();
    
        Student<int,string> stu1(23,"lisi");
        stu1.showStu();
    }
  • 相关阅读:
    面试题6 重建二叉树
    面试题5 从尾到头打印链表
    面试题4 替换空格
    面试题3 二维数组中查找
    面试题2 单例
    C++ 强制类型转换
    C++ 11 新特性
    STL 函数对象
    STL 算法
    OpenSSH多路复用Multiplexing配置
  • 原文地址:https://www.cnblogs.com/xiaozoui11cl/p/12777776.html
Copyright © 2011-2022 走看看