最近看算法书,想写一些通用的函数实现那些基本的算法,结果第一个就出问题了,如题目说的,C++中把模版函数的声明和定义分别写在了.h和.cpp文件中,导致编译出错。具体是这样的:
BasicAlgorithms.h文件:
#ifndef BASIC_ALGORITHMS_H
#define BASIC_ALGORITHMS_H
#include "stdafx.h"
#include <vector>
using namespace std;
class BasicAlgorithms
{
public:
template<typename Type> void InsertionSort(vector<Type> &);
};
#endif
然后在BasicAlgorithms.cpp文件中实现了InsertionSort()函数:
#include "stdafx.h"
#include "BasicAlgorithms.h"
template <typename Type>
void BasicAlgorithms::InsertionSort(vector<Type> &vec_to_sort)
{
vector<Type>::size_type i=0;
for(vector<Type::size_type j=2;j<vec_to_sort.size();j++)
{
Type key=vec_to_sort[j];
i=j-1;
while(i>0&&vec_to_sort[i]>

在尝试将C++模板函数的声明和定义分别放在.h和.cpp文件时,遇到了编译错误LNK2019。原因是模板函数不支持分离编译,其声明和定义必须在同一个头文件中。为解决此问题,将模板函数的定义移至头文件,并创建新的头文件BasicAlgorithmsImplement.h来包含模板函数的定义,从而避免编译错误。
最低0.47元/天 解锁文章
472

被折叠的 条评论
为什么被折叠?



