读书人

help!请大神帮小弟我看上这段程序有什

发布时间: 2012-10-19 16:53:36 作者: rapoo

help!!!请大神帮我看下这段程序有什么问题
在VS2010下写了一个小程序,但是编译出错,不太明白什么问题,有谁懂得请指正下,谢了先~

C/C++ code
#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


C/C++ code
#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]>key)        {            vec_to_sort[i+1]=vec_to_sort[i];            i--;        }        vec_to_sort[i+1]=key;    }}

上面两个分别是BasicAlgorithms.h 和BasicAlgorithms.cpp文件,现在只是实现一个排序算法。主函数如下:
C/C++ code
#include "stdafx.h"#include "BasicAlgorithms.h"#include <vector>#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){    vector<int> vec(20);    int temp=0;    for(vector<int>::size_type i=0;i<vec.size();i++)    {        temp=rand();        cout<<temp<<endl;        vec.push_back(temp);    }    BasicAlgorithms ba;    ba.InsertionSort(vec);    for(vector<int>::size_type i=0;i<vec.size();i++)    {        cout<<vec[i]<<endl;    }    return 0;}

就是对容器中的20个数进行排序,然后输出。但是编译的时候出现了错误:
error LNK2019: 无法解析的外部符号 "public: void __thiscall BasicAlgorithms::InsertionSort<int>(class std::vector<int,class std::allocator<int> > &)" (??$InsertionSort@H@BasicAlgorithms@@QAEXAAV?$vector@HV?$allocator@H@std@@@std@@@Z),该符号在函数 _wmain 中被引用。

[解决办法]
把BasicAlgorithms.cpp中的函数定义放到BasicAlgorithms.h中去。
模版函数的定义和声明是不容许分离的。
否则无法链接上函数,会报链接错误error LNK2019:
[解决办法]
楼上正确,
其实这种写法从语法来说是正确的,但是编译器不支持!
包括gcc vc等等都不支持

读书人网 >C++

热点推荐