2011-10-04 9 views
0

vector로 내부적으로 구현 된 템플릿 스택 클래스가 있습니다. 여기 템플릿 클래스에서 C++ 연산자 오버로드

내 (간체) TStack.h의 내용이다 :

#include <vector> 
#include <iostream> 

template<typename T> class TStack; 
template<typename T> TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2); 

template<typename T> 
class TStack { 
    friend TStack<T> operator+<>(const TStack<T> &s1, const TStack<T> &s2); 
    private: 
     std::vector<T> items; 
    public: 
     void printAll() { 
      std::cout << "The content of the stack is: "; 
      typename std::vector<T>::iterator it; 
      for(it = items.begin(); it < items.end(); it++) { 
       std::cout << *it << " "; 
      } 
      std::cout << std::endl; 
     } 
}; 

template<typename T> 
TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2) { 
    TStack<T> result = s1; 
    typename std::vector<T>::iterator it; 
    //below is line 41 
    for(it = s2.items.begin(); it < s2.items.end(); it++) { 
     result.items.push_back(*it); 
    } 
    return result; 
} 

을 그리고 이것은 내 (간체) 주요 클래스 :

#include <iostream> 
#include "TStack.h" 

using namespace std; 

int main(int argc, char *argv[]) { 
    TStack<int> intStack; 
    intStack.push(4); 

    TStack<int> secondIntStack; 
    secondIntStack.push(10); 

    cout << "Addition result: " << endl; 
    //below is line 27 
    TStack<int> result = intStack + secondIntStack; 
    result.printAll(); 
    return 0; 
} 

그리고 이것은 컴파일 결과입니다

In file included from main.cpp:2: 
TStack.h: In function ‘TStack<T> operator+(const TStack<T>&, const TStack<T>&) [with T = int]’: 
main.cpp:27: instantiated from here 
TStack.h:41: error: no match for ‘operator=’ in ‘it = s2->TStack<int>::items.std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]()’ 
/usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >& __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::operator=(const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&) 
make: *** [main.exe] Error 1 

나는 오류 메시지의 의미가 무엇인지 알지 못합니다.

연산자 + 함수에서 printAll() 내부에서 반복기를 가져 오는 데 같은 방법을 사용했지만 연산자 + 함수 내에서 제대로 작동하지 않습니다. 연산자 + 함수에서 반복자를 사용하는 것을 피할 수 있지만이 문제를 해결하는 방법은 궁금합니다.

답변

5

대신 사용 iteratorconst_iterator : s1는 const를 목적

typename std::vector<T>::const_iterator it; 

때문입니다. 그래서 s1.itemss1.items.begin()const_iterator이고, const가 아닌 iterator을 반환한다는 것을 의미하는 const 객체가됩니다. 연산자의


더 나은 구현 +()

당신은 operator+()의 구현을 향상시킬 수 있습니다. 그것은 완전히 당신이 당신의 코드에 직면 iterator의 문제를 피할 수

template<typename T> 
TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2) { 
    TStack<T> result(s1); //use direct copy-initialization 
    result.insert(result.end(), s2.begin(), s2.end()); 
    return result; 
} 

: 대신 수동 루프 및 push_back 기능을 사용하는, 당신은 insert 기능을 사용할 수 있습니다. 대신 const를 참조 값을 기준으로 첫 번째 인수를 승인하면 운영자의 더


더 나은 구현은, 그 더 나은()

입니다 + : 첫 번째로

template<typename T> 
TStack<T> operator+(TStack<T> s1, const TStack<T> &s2) { 
    s1.insert(s1.end(), s2.begin(), s2.end()); //s1 is a copy, after all! 
    return s1; 
} 

인수가 복사본 인 경우 명시 적으로 result이라는 로컬 변수를 만들 필요가 없습니다. s1s2을 추가하고 s1을 반환하면됩니다.

+1

도움 주셔서 감사합니다! – Hery

3

const 이터레이터 (s2.items.begin())를 비 const 반복기에 할당 할 수 없습니다. 사용

typename std::vector<T>::const_iterator it; 
+0

대답 해줘서 고마워,하지만 그는 1 분 빠른 hahaha 답변 때문에 Nawaz에 대한 허용 대답을 주셔야 ... – Hery

+0

아무런 문제가, 어떻게 작동하는거야. – stijn