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;
}

輸出:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM