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() 내부에서 반복기를 가져 오는 데 같은 방법을 사용했지만 연산자 + 함수 내에서 제대로 작동하지 않습니다. 연산자 + 함수에서 반복자를 사용하는 것을 피할 수 있지만이 문제를 해결하는 방법은 궁금합니다.
도움 주셔서 감사합니다! – Hery