加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++之类模板对象作函数参数

发布时间:2020-12-16 09:06:23 所属栏目:百科 来源:网络整理
导读:三种方式: 1.指定传入的类型(这种最常用) 2.参数模板化 3.整个类模板化 #includeiostream 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; }

三种方式:

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,1)">int>& p) {
    p.show();
}
2.参数模板化
template<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 &T的参数类型是:" << typeid(T).name() << endl;
    p.show();
}

 test() {
    Person<int> p(tom",12);
    printPerson1(p);
    printPerson2(p);
    printPerson3(p);
}

int main() {
    test();
    system(pause");
    return 0;
}

输出:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读