朋友模板重载运算符<&lt ;:未解析的外部符号 [英] Friend template overloaded operator <<: unresolved external symbol

查看:93
本文介绍了朋友模板重载运算符<&lt ;:未解析的外部符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了错误的问题

错误LNK2019无法解析的外部符号``类std :: basic_ostream>& __cdecl cop4530 :: operator<<(类std :: basic_ostream>& ;,类rob :: Stack const&)''(?? 6rob @函数_main Project7中引用的@YAAAV?$ basic_ostream @ DU?$ char_traits @ D @ std @@@ std @@ AAV12 @ ABV?$ Stack @ H @ 0 @@ Z)c:\ Users \ Robrik \ documents \ visual studio 2015 \ Projects \ Project7 \ Project7 \ post.obj 1

Error LNK2019 unresolved external symbol "class std::basic_ostream > & __cdecl cop4530::operator<<(class std::basic_ostream > &,class rob::Stack const &)" (??6rob@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV12@ABV?$Stack@H@0@@Z) referenced in function _main Project7 c:\Users\Robrik\documents\visual studio 2015\Projects\Project7\Project7\post.obj 1

现在,post所做的只是调用operator<<

Right now, all that post is doing is calling the operator<<

声明

namespace rob {     

template < typename T> class Stack {
    friend std::ostream& operator<< (std::ostream& os, const Stack<T>& a);
    void print(std::ostream& os, char ofc = ' ') const;
private:
    std::vector<T> arr;
};

定义

template < typename T>
inline std::ostream & rob::operator<<(std::ostream & os, const Stack<T>& a)                {     
    return a.print(os, ' ');
}
template<typename T>
inline void rob::Stack<T>::print(std::ostream & os, char c) const
{
    for (int i = 0; i != arr.size(); i++)
    {
        os << c << arr[i];
    }
    os << '\n';
}

它们分别位于.h文件和.hpp中,我要求运算符不是成员函数(用于赋值).

They are located in a .h file and a .hpp respectively, I require that the operator is not a member function (for assignment).

推荐答案

您还应该在它实际所属的rob名称空间中声明函数签名:

You should as well declare function signature inside rob namespace which it actually belongs:

namespace rob {
template <typename T>
class Stack {
    friend std::ostream& operator<< (std::ostream& os, const Stack<T>& a);
};

template < typename T>
std::ostream& operator<< (std::ostream& os, const Stack<T>& a){
    ...
}

这篇关于朋友模板重载运算符&lt;&lt ;:未解析的外部符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆