C++ //类模板分文件编写问题及解决 //第一中解决方式 直接包含源文件 //第二种解决方法 将.h 和 cpp的内容写到一起,将后缀改为.hpp文件
1 //第一种方式被注释 2 //未被注释是第二种方式 3 //类模板分文件编写问题及解决 4 5 6 #include <iostream> 7 #include <string> 8 #include<fstream> 9 //第一中解决方式 直接包含源文件 10 //#include"person.cpp" 11 12 13 //第二种解决方法 将.h 和 cpp的内容写到一起,将后缀改为.hpp文件 14 15 #include"person.hpp" 16 17 18 using namespace std; 19 // 20 //template<class T1,class T2> 21 //class Person 22 //{ 23 //public: 24 // Person(T1 name,T2 age); 25 // 26 // void showPerson(); 27 // 28 // T1 m_Name; 29 // T2 m_Age; 30 //}; 31 32 //template<class T1,class T2> 33 //Person<T1, T2>::Person(T1 name, T2 age) 34 //{ 35 // this->m_Name = name; 36 // this->m_Age = age; 37 //} 38 // 39 //template<class T1, class T2> 40 //void Person<T1, T2>::showPerson() 41 //{ 42 // cout << "name= " << this->m_Name << " 年龄:" << this->m_Age << endl; 43 //} 44 // 45 void test01() 46 { 47 Person<string, int>p("Jerry", 52); 48 p.showPerson(); 49 } 50 int main() 51 { 52 53 test01(); 54 55 56 system("pause"); 57 58 return 0; 59 60 }
1 person.hpp 2 3 #pragma once 4 #include <iostream> 5 using namespace std; 6 7 #include <string> 8 #include<fstream> 9 10 11 template<class T1, class T2> 12 class Person 13 { 14 public: 15 Person(T1 name, T2 age); 16 17 void showPerson(); 18 19 T1 m_Name; 20 T2 m_Age; 21 }; 22 template<class T1, class T2> 23 Person<T1, T2>::Person(T1 name, T2 age) 24 { 25 this->m_Name = name; 26 this->m_Age = age; 27 } 28 29 template<class T1, class T2> 30 void Person<T1, T2>::showPerson() 31 { 32 cout << "name= " << this->m_Name << " 年龄:" << this->m_Age << endl; 33 }
1 person.cpp 2 3 //#include "person.h" 4 // 5 // 6 //template<class T1, class T2> 7 //Person<T1, T2>::Person(T1 name, T2 age) 8 //{ 9 // this->m_Name = name; 10 // this->m_Age = age; 11 //} 12 // 13 //template<class T1, class T2> 14 //void Person<T1, T2>::showPerson() 15 //{ 16 // cout << "name= " << this->m_Name << " 年龄:" << this->m_Age << endl; 17 //}
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15135951.html