C++模板函数-无法解析的外部符号
来源:互联网 发布:车载 实用 知乎 编辑:程序博客网 时间:2024/06/06 14:23
在网上,看到有类似的问题,经常是写一个头文件,如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;
}
}
再运行主函数,上述问题,就解决了。
欢迎大家交流编程经验,多提宝贵意见,不胜感激!
- C++模板函数-无法解析的外部符号
- 类模板 无法解析的外部符号
- 模板,无法解析的外部符号
- 模板类 error LNK2019: 无法解析的外部符号
- 模板类 error LNK2019: 无法解析的外部符号
- 类模板“无法解析的外部符号”问题
- 模板方法之无法解析的外部符号
- 模板类 error LNK2019: 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 无法解析的外部符号
- 配置一个ubuntu,任我玩耍任我游 (一)
- 最大似然估计算法(简单,通俗易懂)
- 黑马程序员 java提高——张孝详交通灯管理系统
- 导入protobuf源码报错
- in,or,union all的性能对比
- C++模板函数-无法解析的外部符号
- 重置邮箱密码后,第三方程序调用Exchange发送失败
- 点击键盘返回键 程序不退出
- 带姓名成绩单2
- 基于visual Studio2013解决C语言竞赛题之0806平均分
- 期望最大化(EM)算法(讲的很好)
- 树结构的选择
- 什么是ELF,COFF,和PE COFF
- good job!