zoukankan      html  css  js  c++  java
  • c++之类模板对象作函数参数

    三种方式:

    1.指定传入的类型(这种最常用)

    2.参数模板化

    3.整个类模板化

    #include<iostream>
    using namespace std;
    
    template<class T1,class T2>
    class Person {
    public:
        T1 name;
        T2 age;
        Person(T1 name, T2 age) {
            this->name = name;
            this->age = age;
        }
        void show() {
            cout << "姓名是:" << this->name << " " << "年龄是:" << this->age << endl;
        }
    };
    
    //1.指定传入类型
    void printPerson1(Person<string, int>& p) {
        p.show();
    }
    //2.参数模板化
    template<class T1,class T2>
    void printPerson2(Person<T1,T2> &p) {
        cout << "T1的参数类型是:" << typeid(T1).name() << endl;
        cout << "T2的参数类型是:" << typeid(T2).name() << endl;
        p.show();
    }
    //3.整个类模板化
    template<class T>
    void printPerson3(T &p) {
        cout << "T的参数类型是:" << typeid(T).name() << endl;
        p.show();
    }
    
    void test() {
        Person<string,int> p("tom", 12);
        printPerson1(p);
        printPerson2(p);
        printPerson3(p);
    }
    
    int main() {
        test();
        system("pause");
        return 0;
    }

    输出:

  • 相关阅读:
    公平锁,非公平锁,乐观锁,悲观锁
    需求分析
    需求的获取渠道
    php将中文字符串分割为数组
    面试题
    ecshop中错误
    应用上线前必须进行的10个QA测试
    资料1
    tp数据库配置
    Web开发思路
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12107433.html
Copyright © 2011-2022 走看看