C++模板类头文件和实现文件分离的方法

本文介绍了三种实现C++模板类头文件与实现文件分离的方法,包括使用预处理宏、直接包含实现文件以及在头文件中声明并在单独的CPP文件中定义等方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何实现C++模板类头文件和实现文件分离,这个问题和编译器有关。

第一种方法:bruceteen提出的:使用define

在类模板头文件template_compile.h中: 

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.   base() {};  
  6.   ~base() {};  
  7.   T add_base(T x,T y);  
  8. };  
  9. #define FUCK  
  10. #include "template_compile.cpp"  
  在类模板的实现文件template_compile.cpp中:  
  1. #ifdef FUCK  
  2. template<class T>  
  3. base<T>::add_base(T x,T y)  
  4. {  
  5.   return x+y;  
  6. }  
  7. #endif  
  测试文件不变。

方法二:在类模板头文件template_compile.h中: 

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.     base() {};  
  6.     ~base() {};  
  7.     T add_base(T x,T y);  
  8. };  
  在类模板的实现文件template_compile.cpp中:
  1. #include "template_compile.h"  
  2. template<class T>  
  3. base<T>::add_base(T x,T y)  
  4. {  
  5.     return x+y;  
  6. }  
  在使用模板的测试文件use_template.cpp中:使用#include "template_compile.cpp"  
  1. #include<iostream>  
  2. #include "template_compile.cpp"  
  3. using namespace std;  
  4. void main()  
  5. {  
  6.     base<int> bobj;  
  7.     cout<<bobj.add_base(2,3)<<endl;  
  8. }  

第三种方法:在类模板头文件template_compile.h中: (经验证,好像不行)

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.     base() {};  
  6.     ~base() {};  
  7.     T add_base(T x,T y);  
  8. };  
  9. #include "template_compile.cpp"  
    在类模板的实现文件template_compile.cpp中:  
  1. template<class T>  
  2. T base<T>::add_base(T x,T y)  
  3. {  
  4.     return x+y;  
  5. }  
  在使用模板的测试文件use_template.cpp中:  
  1. #include<iostream>  
  2. #include "template_compile.h"  
  3. using namespace std;  
  4. void main()  
  5. {  
  6.     base<int> bobj;  
  7.     cout<<bobj.add_base(2,3)<<endl;  
  8. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值