2014-10-22 2 views
1

forward_list를 사용하여 스택을 다시 작성하려고합니다. 그러나 친구 기능을 사용하여 + 및 < < 연산자를 오버로드합니다. 난 내 주요 같은에서 그들에게 전화 할 때 내가, 링커 오류가 친구의 기능을 모두 들어 friend 함수가있는 템플릿 클래스의 링커 오류

#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

+0

친구를 사용하고 싶은 특별한 이유가 있습니까? –

+0

@Ajay 아니, 구현 대체는 위 코드에있는 헤더에 구현되어 있습니다. – amaik

답변

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 문서를 사용하고 있기 때문에.

관련 문제