So I have this assignment to create a dynamic stack with template and I've got it nailed pretty much. My question, though, is: I tried to implement "stack2" originally with data type as string. It would not work. The compiler threw all kinds of errors. Could somebody tell me what's wrong with this? If i change it to char* it works just fine.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
template <class T>
class Stack {
public:
Stack();
void push(T i);
T pop();
private:
int top;
T st[100];
};
template <class T>
Stack<T>::Stack() {
top = -1;
}
template <class T>
void Stack<T>::push(T i) {
st[++top] = i;
}
template <class T>
T Stack<T>::pop() {
return st[top--];
}
int main() {
cout << "Demonstration of a dynamic stack with template.\n" << endl;
cout << "Integer stack:\n" << endl;
Stack<int> stack1;
cout << "Pushing 5." << endl;
stack1.push( 5 );
cout << "Pushing 10." << endl;
stack1.push( 10 );
cout << "Pushing 15." << endl;
stack1.push( 15 );
cout << "\nPopping..." << endl;
cout << stack1.pop() << endl;
cout << stack1.pop() << endl;
cout << stack1.pop() << endl;
cout << "\nString (actually char*) stack:\n" << endl;
Stack<string> stack2;
cout << "Pushing \"test\"." << endl;
stack2.push( "test" );
cout << "Pushing \"stack\"." << endl;
stack2.push( "string" );
cout << "Pushing \"string\"." << endl;
stack2.push( "stack" );
cout << "\nPopping..." << endl;
cout << stack2.pop() << endl;
cout << stack2.pop() << endl;
cout << stack2.pop() << endl;
return 0;
}
This is the type of error I am getting:
g:\school\csis 297\assignments\assignment 10\chapter18_challenge2_dynstacktemplate\chapter18_challenge2_dynstacktemplate\stacktest.cpp(55): error C2065: 'string' : undeclared identifier
g:\school\csis 297\assignments\assignment 10\chapter18_challenge2_dynstacktemplate\chapter18_challenge2_dynstacktemplate\stacktest.cpp(58): error C2662: 'Stack<T>::push' : cannot convert 'this' pointer from 'Stack' to 'Stack<T> &'
Reason: cannot convert from 'Stack' to 'Stack<T>'
Conversion requires a second user-defined-conversion operator or constructor