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   廿陆  阅读(48)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示