关于C++类模版的问题

设计一个类模板Sort<T>,其中包含T类型的数组data和其中实际元素个数n,另包含有相关成员函数,用于以选择排序方式对data中的数据进行排序和输出data元素。编写一个主函数定义整数序列和字符序列,并进行排序。
我的程序是:
template<class T>
class Sort
{private:
T *data;
int n;
public:
Sort(T *d,int m);
void display();
~Sort();
};
#include<iostream>
using namespace std;
#include"sort.h"
template <class T>
Sort<T>::Sort(T *d,int m)
{
n=m;
int i,index,j;
T temp;
data=new T[n];
if (data == NULL)
{
cout << "动态数组创建失败!" << endl;
exit(1);
}
for(i=0;i<n;i++)
data[i]=d[i];
for(i=0;i<n-1;i++){
index=i;
for(j=i+1;j<n;j++)
if(d[index]<d[j])
index=j;
temp=d[index];
d[index]=d[i];
d[i]=temp;
}
}
template<class T>
void Sort<T>::display()
{
int k;
for(k=0;k<n;k++)
cout<<data[k];
cout<<endl;
}

template<class T>
Sort<T>::~Sort()
{
delete data;
}
int main()
{
int n,i,*a;
char *b;
cout<<"please input n:";
cin>>n;
a=new int[n];
cout<<"请输入"<<n<<"个整型数";
for (i=0; i < n; i++)
{
cin>>a[i];
}
Sort <int> s1(a,n);
s1.display();
s1.~Sort();
b=new char[n];
cout<<"请输入"<<n<<"个字母";
for (i=0; i < n; i++)
{
cin>>b[i];
}
Sort <char> s2(b,n);
s2.display();
s2.~Sort;
return 0;
}
错误信息是: 搞不清具体错在哪,希望哪位高手可以解答一下
--------------------Configuration: prog2 - Win32 Debug--------------------
Compiling...
main.cpp
H:\prog2\main.cpp(29) : error C2274: '->' : illegal as right side of '.' operator
H:\prog2\main.cpp(29) : error C2274: '->' : illegal as right side of '.' operator
Error executing cl.exe.

main.obj - 2 error(s), 0 warning(s)

#include<iostream>
using namespace std;
template<class T>

class Sort
{private:
T *data;
int n;
public:
Sort(T *d,int m);
void display();
~Sort();
};

template <class T>
Sort<T>::Sort(T *d,int m)
{
n=m;
int i,index,j;
T temp;
data=new T[n];
if (data == NULL)
{
cout << "动态数组创建失败!" << endl;
exit(1);
}
for(i=0;i<n;i++)
data[i]=d[i];
for(i=0;i<n-1;i++){
index=i;
for(j=i+1;j<n;j++)
if(d[index]<d[j])
index=j;
temp=d[index];
d[index]=d[i];
d[i]=temp;
}
}
template<class T>
void Sort<T>::display()
{
int k;
for(k=0;k<n;k++)
cout<<data[k];
cout<<endl;
}

template<class T>
Sort<T>::~Sort()
{
delete data;
}
int main()
{
int n,i,*a;
char *b;
cout<<"please input n:";
cin>>n;
a=new int[n];
cout<<"请输入"<<n<<"个整型数";
for (i=0; i < n; i++)
{
cin>>a[i];
}
Sort <int> s1(a,n);
s1.display();
//s1.~Sort();
b=new char[n];
cout<<"请输入"<<n<<"个字母";
for (i=0; i < n; i++)
{
cin>>b[i];
}
Sort <char> s2(b,n);
s2.display();
//s2.~Sort();
return 0;
}
你为什么要调用析构函数,不明白。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-10-19
不要用分别编译,把模板类的函数定义都放到头文件中去,模板类不支持分别编译.
相似回答