c++模板使用出错情况error LNK2019: unresolved external symbol "public: float __thiscall Compare<float>::min(void)" (?min@?$Compare@M@@QAEMXZ) referenced in function _main
将类模板在头文件中定义,类的成员函数在头文件中声明,头文件中只留下接口,函数的实现在另一个.cpp文件中,这样编译出来错误error LNK2019: unresolved external symbol "public: float __thiscall Compare<float>::min(void)" (?min@?$Compare@M@@QAEMXZ) referenced in function _main。将实现与接口全部在头文件中实现编译就成功了。
error:
class.h
#include<iostream>
#include<cmath>
#include<iomanip>
#include<conio.h>
#include<string>
using namespace std;
template<class T>
class Compare
{
public:
Compare(T x,T y):a(x),b(y){};
T max();
T min();
private:
T a;
T b;
};
class.cpp
#include"class.h"
template<class T>
T Compare<T>::max( )
{
return (a>=b)?a:b;
}
template<class T>
T Compare<T>::min( )
{
return (a<=b)?a:b;
}
right:
#include<iostream>
#include<cmath>
#include<iomanip>
#include<conio.h>
#include<string>
using namespace std;
template<class T>
class Compare
{
public:
Compare(T x,T y):a(x),b(y){};
T max();
T min();
private:
T a;
T b;
};
template<class T>
T Compare<T>::max( )
{
return (a>=b)?a:b;
}
template<class T>
T Compare<T>::min( )
{
return (a<=b)?a:b;
}