类模板“无法解析的外部符号”问题

本文详细介绍了如何解决C++模板函数在主函数中引用解析失败的问题,通过合并模板函数实现与声明,或者使用包含模板实现文件的方式进行改进,确保代码的可读性和便利性。实例演示了具体的解决步骤和方法。

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

http://blog.sina.com.cn/s/blog_68f6e8a901014ljx.html

在上面基础上修改如下

 //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);
#endif

//test.cpp实现文件
#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;
}
}

//在主函数中主函数
#include "test.h"
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,
//头文件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;
}
}
这种方法是很不建议的,因为函数实现的代码,如果特别长的话,影响可读性,而且很多用户调用你的函数时,不关心你的实现,只看函数的输入、输出和作用,都写在一个文件中,增加了很大的不便,建议使用下面的这种方法。
2、 把函数实现文件test.cpp改为test.template.在函数声明头文件test.h结尾处增加#include“test.template”
//test.h头文件
#ifndef _TEST_H
#define _TEST_H

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

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

#include "test.template"
#endif

//test.template实现文件
#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;
}
}

再运行主函数,上述问题,就解决了。(亲测通过)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值