C++ 类模板分文件编写

问题:类模板中成员函数创建时机是在调用阶段导致分文件编写时链接不到

解决:

  1.直接包含   .cpp 源文件

  2.将声明和实现写到同一个文件中,并更改后缀名为 .hpp   hpp是约定名称,并不是强制

1.person.h文件

 1 #pragma once
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 template<class T1,class T2>
 6 class Person
 7 {
 8 public:
 9     Person(T1 name, T2 age);
10     void showPerson();
11     T1 m_Name;
12     T2 m_Age;
13 };

2.person.cpp文件

 1 #include "person.h"
 2 template<class T1, class T2>
 3 Person<T1, T2>::Person(T1 name, T2 age)
 4 {
 5     this->m_Name = name;
 6     this->m_Age = age;
 7 }
 8 template<class T1, class T2>
 9 void Person<T1, T2>::showPerson()
10 {
11     cout << "Name:" << this->m_Name << "\nAge: " << this->m_Age << endl;
12 }

3.Main文件(第一种解决方式)

 1 #include <iostream>
 2 using namespace std;
 3 //#include "person.h" 错误 外部命令无法解析
 4 #include "person.cpp"//正确
 5 void test()
 6 {
 7     Person<string, int>p("tom", 22);
 8     p.showPerson();
 9 }
10 int main()
11 {
12     test();
13     system("pause");
14     return 0;
15 }

第二种解决方式:

将  .h   和  .cpp 内容写到一起  将后缀名改为 .hpp文件  

1.    .hpp文件

 1 #pragma once
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 template<class T1,class T2>
 6 class Person
 7 {
 8 public:
 9     Person(T1 name, T2 age);
10     void showPerson();
11     T1 m_Name;
12     T2 m_Age;
13 };
14 template<class T1, class T2>
15 Person<T1, T2>::Person(T1 name, T2 age)
16 {
17     this->m_Name = name;
18     this->m_Age = age;
19 }
20 template<class T1, class T2>
21 void Person<T1, T2>::showPerson()
22 {
23     cout << "Name:" << this->m_Name << "\nAge: " << this->m_Age << endl;
24 }

2.  Main文件

 1 #include <iostream>
 2 using namespace std;
 3 #include "person.hpp"//正确
 4 void test()
 5 {
 6     Person<string, int>p("tom", 22);
 7     p.showPerson();
 8 }
 9 int main()
10 {
11     test();
12     system("pause");
13     return 0;
14 }

posted on 2023-08-18 23:10  廿陆  阅读(99)  评论(0)    收藏  举报

导航