以下模版类哪里错了
Sort.h
- C/C++ code
template<class T> class Sort{public: void BubblerSort(T * arr,int n);};Sort.cpp
- C/C++ code
#include "Sort.h"template<class T> void Sort<T>::BubblerSort(T * arr,int n){ T temp; for (int i=0;i<n-1;i++) { for (int j=0;j<n-1-i;j++) { if (arr[j]>arr[j+1])//交换相邻的两个数 { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } }}main.cpp
- C/C++ code
#include <iostream>#include <Windows.h>#include "Sort.h"using namespace std;class sort2{public: void BubblerSort(int * arr,int n) { int temp; for (int i=0;i<n-1;i++) { for (int j=0;j<n-1-i;j++) { if (arr[j]>arr[j+1])//交换相邻的两个数 { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } }};void bubbler_sort(int *arr,int n);int main(){ int arr[10]={2,3,1,4,6,7,9,8,0,5}; //bubbler_sort(arr,10); Sort<int> sort; //sort2 sort; sort.BubblerSort(arr,10); for (int i=0;i<10;i++) { cout<<arr[i]<<" "; } cout<<endl; system("pause"); return 0;}求大神解释一下
[解决办法]
模板不支持分离编译,需要把定义也写在头文件中。
[解决办法]
Sort.cpp的代码全部放到Sort.h里
[解决办法]
如果没有其他错误的话, 就是2楼和3楼说的模板分离编译的问题, 目前大多编译器还不支持. 当然, 你可以试试在.h文件的最后加上一句#include"Sort.cpp"(先把Sort.cpp前面的include去掉), 这样可以实现"伪分离编译".