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

Recommended Answers

All 2 Replies

Shall we start with the fact that the standard string class is in the std namespace? You're treating it as if it's in the global namespace.

Ah crap, that's it. I totally spaced that. I just recently ( like yesterday ) stopped using the entire namespace after a conversation came up about it in another thread. Just so used to having it included I totally forgot to look there. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.