可能重复:
模板运算符重载函数上的未定义符号
这是我的源代码。在Number.h
#ifndef NUMBER_H
#define NUMBER_H
#include <iostream>
using std::istream;
using std::ostream;
template <class T> class Number;
template <class T>
ostream& operator<<(ostream&, const Number<T>&);
template <class T>
istream& operator>>(istream&, Number<T>&);
template <class T>
class Number{
public:
Number(const T &n) :i(n) {}
Number() :i(0) {}
T& operator+(const Number&rhs) const;
T& operator-(const Number&rhs) const;
T& operator*(const Number&rhs) const;
T& operator/(const Number&rhs) const;
friend ostream& operator<< <T> (ostream& , const Number<T>&);
friend istream& operator>> <T> (istream& , Number<T>&);
private:
T i;
};
#endif
而在Number.cpp
#include "Number.h"
template<class T>
T& Number<T>::operator+(const Number&rhs) const
{
return i+rhs.i;
}
template<class T>
T& Number<T>::operator-(const Number&rhs) const
{
return i-rhs.i;
}
template<class T>
T& Number<T>::operator*(const Number&rhs) const
{
return i*rhs.i;
}
template<class T>
T& Number<T>::operator/(const Number&rhs) const
{
return i/rhs.i;
}
template<class T>
ostream& operator<<(ostream&os , const Number<T>&rhs)
{
return os<< rhs.i;
}
template<class T>
istream& operator>>(istream&is , Number<T>&rhs)
{
return is >> rhs.i;
}
我不知道为什么有
undefined reference to `std::istream& operator>><double>(std::istream&,Number<double>&)'
undefined reference to `Number<double>::operator+(Number<double> const&) const'
错误等等