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;
}
}
再運行主函數,上述問題,就解決了。


歡迎大家交流編程經驗,多提寶貴意見,不勝感激!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章