將類模板中的成員函式在類模板外定義要注意的地方
阿新 • • 發佈:2018-12-13
1、在宣告類前要有類模板的宣告
2、每個成員函式在模板外定義的時候前面都要有類模板的宣告,注意是每個。
#include<iostream> using namespace std; template<class numtype> //類模板宣告 class compare { public: compare(numtype a,numtype b) { x=a; y=b; } numtype max(); numtype min(); private: numtype x,y; }; template <class numtype> //類模板宣告 numtype compare <numtype>::max() { return x>y?x:y; }; template <class numtype> //類模板宣告 numtype compare <numtype>::min() { return x<y?x:y; }; int main() { compare <int> comp1(3,7); cout<<comp1.max()<<endl<<comp1.min()<<endl; return 0; }