C++中如何在类模板外定义函数

#include<iostream>
using namespace std;
template<class numtype>
class Compare
{ private:
numtype x;
numtype y;
public:
Compare(numtype a,numtype b)
{
x=a;
y=b;
}
numtype max()
{
return (x>y)? x:y;
}
numtype min()
{
return (x<y)? x:y;
}
};
int main()
{
Compare<int>cmp1(3,7);
cout<<cmp1.max()<<endl;
cout<<cmp1.min()<<endl;
Compare<float>cmp2(23.12,43.55);
cout<<cmp2.max()<<endl;
cout<<cmp2.min()<<endl;
Compare<char>cmp3('a','d');
cout<<cmp3.max()<<endl;
cout<<cmp3.min()<<endl;
return 0;
}

是想定义在源文件吗?
1.这是不允许的,因为模板类的成员函数的定义,是一种不完整的定义.
2.由于编译器不知道模板参数的具体类型,无法为其成员函数生成代码.
3.编译器在成员函数的调用处,才最终知道如何生成代码.
总之,模板类的成员函数的定义不能像普通类的成员函数一样,定义在源代码中,而只能定义在头文件中.

如果想定义在头文件中的模板类以外,倒是可以做到,如下:
template<class numtype>
Compare<numtype>::Compare(numtype a,numtype b){
x = a;
y = b;
}

template<class numtype>
numtype Compare<numtype>::max(){
return (x>y)? x:y;
}

template<class numtype>
numtype Compare<numtype>::min(){
return (x<y)? x:y;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2015-08-06
  目前的大多数compiler还不能解析在类的声明之外定义的member template。
  C++ standard 对于在类定义之外定义member template 的标准写法如下(不过在VC++6.0下无法编译通过):
  template <class T> template <class T1>
  void A<T>::Test(T1 p)
  { }
第2个回答  2010-04-11
#include<iostream>
using namespace std;

template<class numtype>
class Compare
{
private:
numtype x;
numtype y;
public:
Compare(numtype,numtype);
numtype max();
numtype min();
};
// 在类模板外面定义其成员函数:
template<class numtype>
Compare<numtype>::Compare(numtype a,numtype b){
x = a;
y = b;
}

template<class numtype>
numtype Compare<numtype>::max(){
return (x>y)? x:y;
}

template<class numtype>
numtype Compare<numtype>::min(){
return (x<y)? x:y;
}本回答被提问者和网友采纳
第3个回答  2010-04-10
同样的定义一个模板函数。
第4个回答  2018-07-25
类模板的成员函数的实现写在头文件(.h)的类内部或类外部都行,

但是,类模板成员函数在另一个文件(.cpp)里实现它报错
error LNK2019: 无法解析的外部符号 "public: void __thiscall Compare<float>::test(void)" (?test@?$Compare@M@@QAEXXZ),该符号在函数 _main 中被引用
相似回答