• 类模板做函数参数


    三种方式

    • 显示指定类型
    • 参数模板化
    • 整体模板化

    实例:

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    
    //类模板
    template<class NameT, class AgeT> //类模板可以有默认类型
    class Person
    {
    public:
        Person(NameT name, AgeT age)
        {
            this->m_Name = name;
            this->m_Age = age;
        }
        void showPerson()
        {
            cout << "姓名:" << this->m_Name << " 年龄: " << this->m_Age << endl;
        }
    
        NameT m_Name;
        AgeT m_Age;
    };
    //1.指定传入的类型
    void doWork(Person<string, int>& p)
    {
        p.showPerson();
    }
    void test01()
    {
        Person<string, int> p("大圣", 500);
        doWork(p);
    }
    //2.参数模板化
    template<class T1, class T2>
    void doWork2(Person<T1, T2>& p)
    {
        //查看传入的参数类型
        cout << "T1的类型:" << typeid(T1).name() << endl;
        cout << "T2的类型:" << typeid(T2).name() << endl;
        p.showPerson();
    }
    void test02()
    {
        Person<string, int> p("唐长老", 100);
        doWork2(p);
    }
    //3.整体模板化
    template<class T>
    void doWork3(T& p)
    {
        cout << "T的类型:" << typeid(T).name() << endl;
    
        p.showPerson();
    }
    void test03()
    {
        Person<string, int> p("娜美", 18);
        doWork3(p);
    }
    int main()
    {
        test01();
        cout << "-------------------------" << endl;
        test02();
        cout << "-------------------------" << endl;
        test03();
        system("Pause");
        return 0;
    }

    结果:

  • 相关阅读:
    序列化
    执行mysql脚本
    MinGW-notepad++开发c/c++程序
    MySql免安装版配置方法
    Wamp 简单使用方法
    [锋利JQ]-图片提示效果
    [锋利的JQ]-超链接提示效果
    PHPcms 系统简单使用
    NC帮助文档网址
    NC的开发模型
  • 原文地址:https://www.cnblogs.com/yifengs/p/15181006.html
Copyright © 2020-2023  润新知