类模板分文件编写(9)
学习目标:
掌握类模板 成员函数分文件编写产生的问题以及解决方式
问题:
类模板成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
解决方式1:直接包含.cpp源文件
1 /*person.h文件*/ 2 #pragma once 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 template<class T1, class T2> 8 class Person 9 { 10 public: 11 12 Person(T1 name, T2 age); 13 14 void showPerson(void); 15 16 T1 m_Name; 17 T2 m_Age; 18 };
/*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 << endl; cout << "年龄:" << this->m_Age << endl; }
#include <iostream> //#include "person.h"//只包含.h,主函数看不到.cpp #include "person.cpp"//.cpp包含.h,主函数能看到.cpp、.h using namespace std; //类模板分文件编写的问题以及解决 //template<class T1,class T2> //class Person //{ //public: // // Person(T1 name, T2 age); // // void showPerson(void); // // T1 m_Name; // T2 m_Age; //}; //类模板构造函数的类外实现 //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 << endl; // cout << "年龄:" << this->m_Age << endl; //} void test_01(void) { Person<string, int>p("Jerry", 18); p.showPerson(); } int main(void) { test_01(); system("pause"); return 0; }
解决方式2:将类模板的声明和实现写到同一个文件中,并更改后缀名为.hpp,在主函数调用的时候包含".hpp"头文件就可以了
1 /*person.hpp*/ 2 #pragma once 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 template<class T1, class T2> 8 class Person 9 { 10 public: 11 12 Person(T1 name, T2 age); 13 14 void showPerson(void); 15 16 T1 m_Name; 17 T2 m_Age; 18 }; 19 20 template<class T1, class T2> 21 Person<T1, T2>::Person(T1 name, T2 age) 22 { 23 this->m_Name = name; 24 this->m_Age = age; 25 } 26 27 template<class T1, class T2> 28 void Person<T1, T2>::showPerson() 29 { 30 cout << "姓名:" << this->m_Name << endl; 31 cout << "年龄:" << this->m_Age << endl; 32 }
1 #include <iostream> 2 #include <string> 3 #include "person.hpp" //直接包含.hpp头文件 4 using namespace std; 5 6 void test_01(void) 7 { 8 Person<string, int>p("Jerry", 18); 9 p.showPerson(); 10 } 11 12 int main(void) 13 { 14 test_01(); 15 16 system("pause"); 17 return 0; 18 }