Pat*_*ouf 1 c++ inheritance templates
我在从模板类继承时遇到一些问题。下面的代码无法编译,显示此错误:main.cpp : undefined reference to OBJ1<1000>::method()
父级.h
template <int nb>
class PARENT
{
PARENT() {};
~PARENT() {};
virtual void method() = 0;
enum { nb_ = nb };
};
Run Code Online (Sandbox Code Playgroud)
对象1.h
#include "parent.h"
template <int nb>
class OBJ1 : public PARENT<nb>
{
virtual void method();
};
Run Code Online (Sandbox Code Playgroud)
对象1.cpp
#include "obj1.h"
template <int nb>
void OBJ1<nb>::method()
{
//code
}
Run Code Online (Sandbox Code Playgroud)
主程序
#include "obj1.h"
int main()
{
OBJ1<1000> toto;
toto.method();
}
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
处理模板时,您不能将声明和实现拆分为单独的文件。请参阅此问题了解原因(以及解决此问题的更简洁的描述)。
这需要合并(您也可以将#include实现文件放入标头中,让预处理器进行合并。):
// obj1.hpp
#include "parent.h"
template <int nb>
class OBJ1 : public PARENT<nb>
{
virtual void method();
};
template <int nb>
void OBJ1<nb>::method()
{
//code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1040 次 |
| 最近记录: |