I am new to C ++, but already got some experience in java.
In the next short C ++ exercise, I tried to create a stack using a class template. Unfortunately, it does not compile, and I cannot understand why.
Error message:
Stack.cpp: 6: error: expected constructor, destructor or type conversion before the token ‘<’
Stack.cpp: 14: error: expected initializer before the token ‘<’
Stack.cpp: 25: error: expected initializer before the token ‘<’
make [2]: * [build / Debug / GNU-Linux-x86 / Stack.o] Error 1
Here is Stack.h:
template <class T>
class Stack {
public:
Stack(int = 10);
~Stack() {
delete [] stackPtr;
}
int isEmpty()const {
return top == -1;
}
int isFull() const {
return top == size - 1;
}
int push(const T&);
int pop(T&);
private:
int size; // length i.e. number of elements on Stack.
int top; //index of top element
T* stackPtr;
};
Stack.cpp:
template <class T>
Stack<T>::Stack(int s) {
size = s > 0 && s < 1000 ? s : 15;
top = -1; // initialize stack
stackPtr = new T[size];
}
template <class T>
int Stack<T>::push(const T& item) {
if (!isFull()) {
stackPtr[++top] = item;
return 1; // push successful
}
return 0; // push unsuccessful
}
template <class T>
int Stack<T>::pop(T& popValue) {
if (!isEmpty()) {
popValue = stackPtr[top--];
return 1; // pop successful
}
return 0; // pop unsuccessful
}
The main.cpp file looks like this:
#include <iostream>
#include "Stack.h"
using namespace std;
int main(int argc, char** argv) {
Stack<int> intStack;
int i = 1.1;
cout << "Pushing:" << endl;
while (intStack.push(i)) {
cout << i << ' ';
i += 1;
}
cout << endl << "Stack Full" << endl
<< endl << "Popping elements from is" << endl;
while (intStack.pop(i))
cout << i << ' ';
cout << endl << "Stack Empty" << endl;
}
What is wrong here?