C++模板函数-无法解析的外部符号

在网上,看到有类似的问题,经常是写一个头文件,如test.h,里面这样写:
#ifndef _TEST_H
#define _TEST_H
#include
using namespace std;

//给指针data分配height*width的内存
template
void Allocate(Item*& data, int height, int width);

//输出data中的数据
template
void Print(Item* data, int height, int width);
#endif
然后写cpp文件,命名为test.cpp,
//test.cpp
#include
#include "test.h"
template
void Allocate(Item*& data, int height, int width)
{
data = new Item[height*width];
for(int i=0; i
for(int j=0; j
data[i*width+j] = 0;
}

template
void Print(Item* data, int height, int width)
{
for(int i=0; i
{
for(int j=0; j
std::cout<<data[i*width+j]<<"\t";
std::cout<<endl;
}
}
//主函数
void main()
{
int* data;
Allocate(data, 10, 10);
Print(data, 10, 10);
system("pause");
}
然后出现这样的问题:
maint.obj : error LNK2019: 无法解析的外部符号 "void __cdecl Print(int *,int,int)" (??$Print@H@@YAXPAHHH@Z),该符号在函数 _main 中被引用
maint.obj : error LNK2019: 无法解析的外部符号 "void __cdecl Allocate(int * &,int,int)" (??$Allocate@H@@YAXAAPAHHH@Z),该符号在函数 _main 中被引用
E:\exercise\TempTest1\Debug\TempTest1.exe : fatal error LNK1120: 2 个无法解析的外部命令
解决方案:
1、将实现函数和声明函数合并在一起,即将test.cpp和test.h相合并,即直接写为test.h,
#include
template
void Allocate(Item*& data, int height, int width)
{
data = new Item[height*width];
for(int i=0; i
for(int j=0; j
data[i*width+j] = 0;
}
template
void Print(Item* data, int height, int width)
{
for(int i=0; i
{
for(int j=0; j
std::cout<<data[i*width+j]<<"\t";
std::cout<<endl;
}
}
//主函数

这种方法是很不建议的,因为函数实现的代码,如果特别长的话,影响可读性,而且很多用户调用你的函数时,不关心你的实现,只看函数的输入、输出和作用,都写在一个文件中,增加了很大的不便,建议使用下面的这种方法。
2、在头文件下面增加包含文件“test.template”,即
//test.h
#ifndef _TEST_H
#define _TEST_H
#include
using namespace std;

template
void Allocate(Item*& data, int height, int width);

template
void Print(Item* data, int height, int width);
#include "test.template"
#endif
然后写test.template文件,直接新建,文件名写为“test.template”,
然后在这个文件中,实现函数功能,如下:
#include
template
void Allocate(Item*& data, int height, int width)
{
data = new Item[height*width];
for(int i=0; i
for(int j=0; j
data[i*width+j] = 0;
}

template
void Print(Item* data, int height, int width)
{
for(int i=0; i
{
for(int j=0; j
std::cout<<data[i*width+j]<<"\t";
std::cout<<endl;
}
}
再运行主函数,上述问题,就解决了。


欢迎大家交流编程经验,多提宝贵意见,不胜感激!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章