重载模板类的运算符<<时获取链接器错误

get linker error while overloading operator << for template class

本文关键字:lt 获取 链接 错误 运算符 重载      更新时间:2023-10-16

我使用visualc++。我有一个模板类,我想为它添加重叠操作我像下面这样实现在头文件

    template <class T> class QuantityT;
    template <class T>
    inline std::ostream & operator<< (std::ostream & os,const QuantityT<T> &quantity);

    template <class T>
    class QuantityT{
            T quantity_;
            template<class T> friend inline std::ostream & operator<< <T>(std::ostream & os,const QuantityT<T> &quantity);
    };

源文件

    template <class T>
    inline std::ostream & operator<< (std::ostream & os,const QuantityT<T> &quantity){
    }

但是我得到链接错误:

主要。obj: error LNK2019:未解析的外部符号类Std::basic_ostream> &__cdecloperator<<(类std::basic_ostream> &,类QuantityT const &)"(? ? ?美元6 k@@yaaav ? basic_ostream@DU美元? char_traits@D@std@@@std@@AAV01@ABV美元? QuantityT@K@@@Z美元)在函数"public: virtual void __thiscall "中引用日志::打印(类std:: basic_ostream

&)const " (?print@log@@UBEXAAV?$basic_ostream@DU?美元char_traits@D@std@@@std@@@Z

我该如何修复它?

尝试将源文件的内容放入头文件:

template <class T>
inline std::ostream & operator<< (std::ostream & os,const QuantityT<T> &quantity){
}

查看这个问题了解更多信息