#include <iostream>
using namespace std;
#define OUT(x) cout << (x) << endl;
template<class T, int size> class Stack{
T arr[size];
int top;
public:
Stack():top(-1){}
void push(T obj);
T pop();
};
template<class T, int size> void Stack<T,size>::push(T obj){
top++;
if(top >= size){
top--;
OUT("the stack is full");
}else{
arr[top] = obj;
}
}
template<class T, int size> T Stack<T,size>::pop(){
if(top < 0){
OUT("the stack is empty");
return NULL;
}else{
T obj = arr[top];
arr[top] == NULL;
top--;
return obj;
}
}
int main() {
Stack<int, 5> intStack;
for(int i = 0; i < 5; i++)
intStack.push(i);
for(int i = 0; i < 5; i++)
OUT(intStack.pop())
return 0;
}
The code above works fine without any compile time or runtime errors, but when i add this to the main function:
Stack<string, 5> strStack;
for(int i = 0; i < 5; i++)
strStack.push("hello");
for(int i = 0; i < 5; i++)
OUT(strStack.pop())
and when i compile the code, it gives me these error messages:
(i test this on eclipse)
make all
Building file: ../src/Stack.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Stack.d" -MT"src/Stack.d" -o"src/Stack.o" "../src/Stack.cpp"
../src/Stack.cpp: In member function ‘T Stack<T, size>::pop() [with T = int, int size = 5]’:
../src/Stack.cpp:39: instantiated from here
../src/Stack.cpp:28: warning: NULL used in arithmetic
../src/Stack.cpp:28: warning: statement has no effect
../src/Stack.cpp: In member function ‘T Stack<T, size>::pop() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int size = 5]’:
../src/Stack.cpp:45: instantiated from here
../src/Stack.cpp:28: error: no match for ‘operator==’ in ‘((Stack<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, 5>*)this)->Stack<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, 5>::arr[((Stack<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, 5>*)this)->Stack<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, 5>::top] == 0’
make: *** [src/Stack.o] Error 1