c++类模板之分文件编写问题及解决
我们在实际项目中一般习惯头文件(.h)和源文件(.cpp)分开写,这样做的好处良多,但是如果遇到了类模板,这样可能会有一点儿问题。
我们通过一个例子来看:
person.h:
1 #pragma once 2 #include<string> 3 #include<iostream> 4 using namespace std; 5 6 template<class nameType,class ageType> 7 class Person { 8 public: 9 Person(nameType name, ageType age); 10 void show(); 11 nameType m_Name; 12 ageType m_Age; 13 };
person.cpp:
1 #include"person.h" 2 3 template<class nameType,class ageType> 4 Person<nameType, ageType>::Person(nameType name,ageType age) 5 { 6 this->m_Name = name; 7 this->m_Age = age; 8 } 9 10 template<class nameType,class ageType> 11 void Person<nameType, ageType>::show() 12 { 13 cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl; 14 }
main.cpp:
1 #include<iostream> 2 using namespace std; 3 #include "person.h" 4 void test() 5 { 6 Person<string, int> p("张三", 18); 7 p.show(); 8 } 9 int main() 10 { 11 test(); 12 system("pause"); 13 return EXIT_SUCCESS; 14 }
编译发现如下错误:

错误原因分析:
由于类模板的成员函数是运行时才会创建,所以分文件编写时编译器找不到成员函数的实现
问题解决:
方法一(不推荐)
直接在main.cpp里将person.cpp包含进来,如下所示:
1 #include<iostream> 2 using namespace std; 3 #include "person.cpp" 4 void test() 5 { 6 Person<string, int> p("张三", 18); 7 p.show(); 8 } 9 int main() 10 { 11 test(); 12 system("pause"); 13 return EXIT_SUCCESS; 14 }
方法二(推荐)
将person.h、person.cpp的内容全部放入同一个文件person.hpp中,然后在main.cpp中将person.hpp包含进来即可
person.hpp:
1 #pragma once 2 #include<string> 3 #include<iostream> 4 using namespace std; 5 6 template<class nameType,class ageType> 7 class Person { 8 public: 9 Person(nameType name, ageType age); 10 void show(); 11 nameType m_Name; 12 ageType m_Age; 13 }; 14 15 template<class nameType, class ageType> 16 Person<nameType, ageType>::Person(nameType name, ageType age) 17 { 18 this->m_Name = name; 19 this->m_Age = age; 20 } 21 22 template<class nameType, class ageType> 23 void Person<nameType, ageType>::show() 24 { 25 cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl; 26 }
main.cpp:
1 #include<iostream> 2 using namespace std; 3 #include "person.hpp" 4 void test() 5 { 6 Person<string, int> p("张三", 18); 7 p.show(); 8 } 9 int main() 10 { 11 test(); 12 system("pause"); 13 return EXIT_SUCCESS; 14 }
运行结果:

总结:模板类不要分文件编写,写到一个类中即可

浙公网安备 33010602011771号