2014-10-22 70 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文檔。