類模板的分文件編寫

將類模板成員函數(shù)寫道一起,并且改為“hpp”,看到這個(gè)dalao們肯定知道只是類模板了

person.hpp代碼

#pragma once
#include <iostream>
using namespace std;
//類模板中的函數(shù)類外實(shí)現(xiàn)
template<class T1, class T2>
class Person
{
    //成員函數(shù)類聲明
public:
    Person(T1 name, T2 age);
    void show();
public:
    T1 my_name;
    T2 my_age;
};
//構(gòu)造函數(shù) 類外實(shí)現(xiàn)
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
    this->my_name = name;
    this->my_age = age;
}
//成員函數(shù) 類外實(shí)現(xiàn)
template<class T1, class T2>
void Person<T1, T2>::show()
{
    cout << "姓名: " << this->my_name << " " << "年齡 " << this->my_age << endl;
}

類模板分文件“.cpp”代碼


#include <iostream>
using namespace std;

#include "person.hpp"

void test01()
{
    Person<string, int>p("吳迪", 20);
    p.show();
}
int main()
{
    test01();
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容