1. 程式人生 > 其它 >類模板的分檔案編寫的問題和解決(要引入.cpp而不是標頭檔案)

類模板的分檔案編寫的問題和解決(要引入.cpp而不是標頭檔案)

標頭檔案

Person.h

#pragma once
#include <iostream>
using namespace std;

template<class T1, class T2>
class Person
{
public:
    Person(T1 name, T2 age);
    void showPerson();

    T1 m_Name;
    T2 m_Age;
};

Person.cpp

#include "Person.h"

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
    
this->m_Name = name; this->m_Age = age; } template<class T1, class T2> void Person<T1, T2>::showPerson() { cout << "姓名:" << this->m_Name << " 年齡: " << this->m_Age << endl; }

main

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using
namespace std; #include "Person.h" void test01() { Person<string, int>p("豬八戒", 30); //error 無法解析的外部命令 p.showPerson(); //error } int main() { test01(); system("Pause"); return 0; }

無法執行:

解決辦法:

main中引入.cpp檔案

結果: