2014-10-22 74 views
1

我正尝试用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 &)" ([email protected][email protected]@@[email protected]@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> &)" ([email protected][email protected][email protected]@[email protected]@@[email protected]@[email protected][email protected]@@@Z) referenced in function _main 

提前致谢。

+0

你在哪里为你的Stack类实现了'operator +'?在一些.CPP文件中? – Ajay 2014-10-22 08:00:14

+0

为什么你想使用朋友的所有特殊原因? – 2014-10-22 08:01:49

+0

@Ajay否它在头部实现,//代码实现在上面的代码中。 – amaik 2014-10-22 08:14:34

回答

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文档。