例如:
这是一个摸板类声明:
test.h
template<class PROCESSOR_IMPL>
class CTestB
{
public:
CTestB(void);
virtual ~CTestB(void);
void Show(void);
};但是如何在cpp文件中定义呢:
例如
test.cpp
template<class PROCESSOR_IMPL>
CTestB<PROCESSOR_IMPL>::CTestB(void)
{
cout<<"CTestB"<<endl;
}
我这样在cpp文件中写,但是却提示错误:
无法解析的外部符号 "public: __thiscall CTestB<int>::CTestB<int>(void)" (??0?$CTestB@H@@QAE@XZ)
这是一个摸板类声明:
test.h
template<class PROCESSOR_IMPL>
class CTestB
{
public:
CTestB(void);
virtual ~CTestB(void);
void Show(void);
};但是如何在cpp文件中定义呢:
例如
test.cpp
template<class PROCESSOR_IMPL>
CTestB<PROCESSOR_IMPL>::CTestB(void)
{
cout<<"CTestB"<<endl;
}
我这样在cpp文件中写,但是却提示错误:
无法解析的外部符号 "public: __thiscall CTestB<int>::CTestB<int>(void)" (??0?$CTestB@H@@QAE@XZ)
模板类是在编译时实例化成类型的,因此你放在另外一个cpp中的实现无法在编译时被实例化(因为模板函数还没有生成符号,只有实例化的函数才有符号,而分在两个cpp文件中的普通函数能编译过就是因为链接时可以找到符号)为了分类编译,你必须在模板类所在的cpp文件中显式为它实例化,或者在头文件中定义,且确保这个头文件被包含那个实现cpp所包含。其语法是:
template<int> CTestB ; //这句话告诉编译,有一个以int为模板参数的实例需要你必须为每种可能的模板参数都实例化,因此这非常麻烦,从而不被建议
但怎么写都不成功.
能否帮我看下,代码如下:
TestB.h 文件
#pragma once
#ifndef TESTB_H
#define TESTB_H
template<typename T>
class CTestB
{
public:
CTestB(void);
virtual ~CTestB(void);
void ShowTest(void);
};
//template <int> class CTestB; /*这样不行*/
template <class T> class CTestB; /*这样才行(显示实例化否则不能在cpp找到实现)*/
#include "TestB.cpp" /*需要显示包含.cpp才行*/
#endif TestB.cpp 文件
#pragma once
#ifndef TESTB_CPP
#define TESTB_CPP
#include "StdAfx.h"
#include "Testb.h"
template<typename T>
CTestB<T>::CTestB(void)
{
std::cout<<"CTestB()"<<std::endl;
}template<typename T>
CTestB<T>::~CTestB(void)
{
std::cout<<"~CTestB()"<<std::endl;
}
template<typename T>
CTestB<T>::ShowTest(void)
{
std::cout<<"hello"<<std::endl;
}
#endif 提示的错误是:
error C2995: “CTestB<T>::CTestB(void)” : 模板函数已经定义
error C2995: “CTestB<T>::~CTestB(void)”: 模板函数已经定义