我尝试使用forward_list重新调整堆栈。但是,我使用友元函数来重载+和<<操作
#pragma once
#include <forward_list>
template <class T> class Stack;
template <class T>
Stack<T> operator+(const Stack<T> &a, const Stack<T> &b){
//implementation
}
template <class T>
std::ostream &operator<<(std::ostream &output, Stack<T> &s)
{
//implementation
}
template <class T>
class Stack
{
friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);
std::forward_list<T> l;
public:
//Some public functions
};
对于这两个朋友函数,我得到一个链接器错误,当我尝试在我的主要调用它们时:
int main(){
Stack<int> st;
st.push(4);
Stack<int> st2;
st2.push(8);
cout<<st + st2<<endl;
return 0;
}
这些是错误:
error LNK2019: unresolved external symbol "class Stack<int> __cdecl operator+(class Stack<int> const &,class Stack<int> const &)" (??H@YA?AV?$Stack@H@@ABV0@0@Z) referenced in function _main
error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Stack<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$Stack@H@@@Z) referenced in function _main
提前致谢。
答案 0 :(得分:2)
Stack类中的模板好友声明不太正确。你需要声明如下:
template<class T>
friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
template<class T>
friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);
由于您使用的是MSVC,请see this Microsoft文档以供进一步参考。